1

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

1 回答 1

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()
于 2013-08-07T11:23:12.090 回答