Scala compiler behaves weirdly with boxing/unboxing in tuples as parameters.
Consider the code:
Welcome to Scala 2.12.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_91).
Type in expressions for evaluation. Or try :help.
scala> class Test { def test(p: (Int, String)) = println(p) }
defined class Test
scala> new Test().test(1, "123")
(1,123)
scala> new Test().test(1.4, "123")
<console>:13: error: too many arguments (2) for method test: (p: (Int, String))Unit
   new Test().test(1.4, "123")
                        ^
scala> // good
scala> classOf[Test].getMethods()(0)
res2: java.lang.reflect.Method = public void Test.test(scala.Tuple2)
scala> classOf[Test].getMethods()(0).getGenericParameterTypes
res3: Array[java.lang.reflect.Type] = Array(scala.Tuple2<java.lang.Object, java.lang.String>)
scala> // WTF??????                                      ^^^^^^^^^^^^^^^^
Thus, I'm getting Object instead of Integer. I assume this is somehow related to tuple parameter being @specialized, but cannot wrap my head around how to avoid/fix this.
The problem it causes - it is impossible to reconstruct method parameter via reflection having method signature (i.g. while parsing json).
Event if there's a way to get the right type with scala-reflect it doesn't help much, cause there are lot of Java libraries around (like Jersey) that uses just Java reflection.
Aucun commentaire:
Enregistrer un commentaire