vendredi 16 septembre 2016

Scala reflection with Int parameter

In the below code, I try to invoke an object's method that has an Int parameter (giving it a value of 3). This returns an error that Int and 3 are incompatible types.

//Using scala's Int does not work!
object MyObject{
  def handleInt(id:Int) : Boolean = {
    true
  }
}

object testApp extends App {
    val obj    = MyObject.getClass
    val method = obj.getDeclaredMethod("handleInt", classOf[Int]) //Int.getClass shows the same behavior
    val rsp    = method.invoke(obj, 3)
}

Error:(106, 41) the result type of an implicit conversion must be more specific than AnyRef

    val rsp    = method.invoke(obj, 3)

Error:(106, 41) type mismatch; found : Int(3) required: Object

    val rsp    = method.invoke(obj, 3)

I tried modifying a lot of things here, the only way this could work is by changing all signatures to Java's Integer. The code will look like this:

//This works with Java's Integer
object MyObject{
  def handleInt(id:Integer) : Boolean = {
    true
  }
}

object testApp extends App {
    val obj    = MyObject.getClass
    val method = obj.getDeclaredMethod("handleInt", classOf[Integer])
    val rsp    = method.invoke(obj, 3)
}

My question(s) are:

  1. Can someone explain why this happens? I think scala's Int wraps java's primitive int (which is why this is not considered an object), but I'm not sure.
  2. Is there a way to achieve this using Scala's Int type?
  3. Is it acceptable to mix scala and java types like this? Is it a good practice?




Aucun commentaire:

Enregistrer un commentaire