Polymorphic instantiation in Scala using TypeTag and ClassTag

旧巷老猫 提交于 2019-12-09 06:27:40

问题


In Scala 2.9 one could implement polymorphic instantiation as

def newInstance[T](implicit m: Manifest[T]) =
    m.erasure.newInstance.asInstanceOf[T]

but as of 2.10 Manifest is being replaced with TypeTag, and it is not clear to me how to achieve something similar with TypeTag. I would prefer if the TypeTag version preserved all available type information.

I know that the above only works for traits/classes that do not require constructor args, and ven then it does not always work, but it works well enough for what I need. If I can do better the new reflection APIs that would be great.


回答1:


TypeTag is not yet a replacement for Manifest because it's a part of experimental and unstable Scala reflection. You definitely shouldn't use it for production as of now.

For the use case you showed, where only runtime class is needed (not full type information with generics etc.), Scala 2.10 introduced ClassTag, which you can use like this:

def newInstance[T: ClassTag] =
  implicitly[ClassTag[T]].runtimeClass.newInstance.asInstanceOf[T]

or:

def newInstance[T](implicit ct: ClassTag[T]) =
  ct.runtimeClass.newInstance.asInstanceOf[T]

Anyway, Manifest isn't deprecated yet, so I guess you can still use it.

EDIT:

Using TypeTag to achieve the same:

import scala.reflect.runtime.universe._

def newInstance[T: TypeTag] = {
  val clazz = typeTag[T].mirror.runtimeClass(typeOf[T])
  clazz.newInstance.asInstanceOf[T]
}

The above solution still uses some Java reflection. If we want to be puristic and use only Scala reflection, this is the solution:

def newInstance[T: TypeTag]: T = {
  val tpe = typeOf[T]

  def fail = throw new IllegalArgumentException(s"Cannot instantiate $tpe")

  val noArgConstructor = tpe.member(nme.CONSTRUCTOR) match {
    case symbol: TermSymbol =>
      symbol.alternatives.collectFirst {
        case constr: MethodSymbol if constr.paramss == Nil || constr.paramss == List(Nil) => constr
      } getOrElse fail

    case NoSymbol => fail
  }
  val classMirror = typeTag[T].mirror.reflectClass(tpe.typeSymbol.asClass)
  classMirror.reflectConstructor(noArgConstructor).apply().asInstanceOf[T]
}



回答2:


If you want to support passing args, here's a trick I do with 2.11:

def newInstance[T : ClassTag](init_args: AnyRef*): T = {
classTag[T].runtimeClass.getConstructors.head.newInstance(init_args: _*).asInstanceOf[T]
}

Example usage:

scala> case class A(x:Double, y:Int)
defined class A
scala> newInstance[A](4.5.asInstanceOf[Object],3.asInstanceOf[Object])
res1: A = A(4.5,3)


来源:https://stackoverflow.com/questions/18499384/polymorphic-instantiation-in-scala-using-typetag-and-classtag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!