vendredi 2 février 2018

Scala Reflection: instantiating a singleton object

I'm using the following code to instantiate a scala object. This works, but there seems to be one problem: the println is printed out twice, each time with another hashcode.

import scala.reflect.runtime.universe._
import scala.reflect.runtime.{universe => ru}
object Test2 { println("init"+hashCode())}
val mirror = ru.runtimeMirror(getClass.getClassLoader)
val m = ru.typeOf[Test2.type].members.filter(_.isConstructor).head.asMethod
val m2 = mirror.reflectClass(typeOf[Test2.type].typeSymbol.asClass)
val cm = m2.reflectConstructor(m)
val e = cm.apply()

Results in:

init472467991
init2051378291
e: Any = Test2$@7a458c73

the hashCode of e is equal to the latter one (2051378291). I'm wondering why this is because as far as I know there should be only one?





Aucun commentaire:

Enregistrer un commentaire