Polymorphic instantiation in Scala using TypeTag and ClassTag

前端 未结 2 472
无人及你
无人及你 2021-02-06 15:16

In Scala 2.9 one could implement polymorphic instantiation as

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


        
2条回答
  •  自闭症患者
    2021-02-06 15:41

    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)
    

提交回复
热议问题