簡體   English   中英

是否可以實例化作為參數傳遞給Scala中的通用特征的類的實例?

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

我有以下用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而失敗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]

所以,最后,我做到了:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM