简体   繁体   中英

Is it possible to instantiate an instance of class, passed as parameter to generic trait in Scala?

I have the following code, written in Scala 2.10.0:

trait A[T <: B] {
  self : { def foo() } =>

  val action : ()=>Unit = this.foo _
  //wanna make default for this
  val construction : String=>T

  def bar()(implicit x : String) : T = {
    action()
    val destination = construction(x)
    destination.baz()
    destination
  }
}

trait B { def baz() {} }

class Xlass { def foo() {} }

class Klass(a : String)(implicit val x : String) extends B {
    val f = new Xlass with A[Klass] {
        //boilerplate!
        val construction = new Klass(_)
    }
}

implicit val x = "Something"
val destination = new Klass("some a").f.bar()

I wonder, is it possible to make a default for construction , such as val construction = new T(_) ? I've tried several options for now, but none of them works with all the characteristics of this code, such as use of type bounds, implicits and structural typing. As far as I could get is this, but it fails with scala.ScalaReflectionException: free type T is not a class :

import reflect.runtime.universe._
val tT = weakTypeTag[T]
...
val privConstruction = 
  x : String => 
    runtimeMirror(tT.mirror.getClass.getClassLoader)
    //fails here with scala.ScalaReflectionException: free type T is not a class 
    .reflectClass(tT.tpe.typeSymbol.asClass) 
    .reflectConstructor(tT.tpe.members.head.asMethod)(x).asInstanceOf[T]

So, finally, I did it:

trait A[T <: B] {
  self : { def foo() } =>

  val action : ()=>Unit = this.foo _
  def construction(x: String)(implicit tag : reflect.ClassTag[T]) : T = {
    tag.runtimeClass.getConstructor(classOf[String], classOf[String]).newInstance(x, x).asInstanceOf[T]
  }

  def bar()(implicit x : String, tag : reflect.ClassTag[T]) : T = {
    action()
    val destination = construction(x)
    destination.baz()
    destination
  }
}

trait B { def baz() {} }

class Xlass { def foo() {} }

class Klass(a : String)(implicit val x : String) extends B {
    val f = new Xlass with A[Klass]
}

implicit val x = "Something"
val destination = new Klass("some a").f.bar()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM