[ACCEPTED]-Convert Scala Any to Java Object-scala-java-interop

Accepted answer
Score: 37

java.lang.Object is equivalent to AnyRef in Scala, not Any. The idea 5 is, Scala Double (roughly equivalent to Java double) is 4 an Any, but not an AnyRef. java.lang.Double is an AnyRef, thus also an 3 Any.

You can simply cast an Any to AnyRef, which will 2 perform the needed conversion to turn a 1 Scala Double into a java.lang.Double:

scala> val x = 3.5
x: Double = 3.5

scala> x.getClass
res0: Class[Double] = double

scala> val y = x.asInstanceOf[AnyRef]
y: AnyRef = 3.5

scala> y.getClass
res1: Class[_ <: AnyRef] = class java.lang.Double
Score: 1

Ok, I was a bit late but here goes:

The 4 following works:

constructor.newInstance(arguments.asInstanceOf[Array[AnyRef]]: _*).asInstanceOf[MyClass]

See also: Transforming Scala varargs into Java Object... varargs

Advice: I'd be 3 very cautious using reflection. In Scala 2 that is bad style. One way to limit/encapsulate 1 it could be:

case class MyClass(id: String, value: Double)     

object MyClass {

    import scala.util.Try
    def apply(map: Map[String, Any] /* this is asking for trouble */) : Option[MyClass]  =  for {
            id <- maybeT[String](map.get("id"))
            value <- maybeT[Double](map.get("value"))
        } yield MyClass(id, value)

    // a truly global utility?
    @inline def maybeT[T] ( a: Any /*Option[T]*/ ) : Option[T]= Try(a.asInstanceOf[Option[T]]).toOption.flatten //yep ugly as hell

}


MyClass(Map("id" -> "CE0D23A", "value" -> 828.32))

More Related questions