简体   繁体   English

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

[英]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: 我有以下用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(_) ? 我想知道,是否可以将construction默认设置为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 : 据我所能获得的,但是它因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]

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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