是否可以实例化一个类的实例,作为参数传递给Scala中的通用特征?

时间:2013-02-25 09:09:25

标签: scala reflection traits scala-2.10

我有以下代码,用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()

我想知道,是否可以为construction设置默认值,例如val construction = new T(_)? 我现在尝试了几个选项,但它们都不适用于此代码的所有特性,例如使用类型边界,隐含和结构类型。我可以得到的是这个,但它失败了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]

1 个答案:

答案 0 :(得分:1)

所以,最后,我做到了:

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()