带有Case Class和Object Companion的Scala泛型

时间:2014-08-08 15:05:10

标签: scala generics reflection

我有这个:

case class Aaa() extends NClass {
  def method1() = println("method1")
}

object Aaa extends NCompanion {
  def method2() = println("method2")
}

我想实现类似下面的伪代码:

abstract class Xxx[T] {
  // All the trash code of reflection/implicit should be in this class only
  instance = new T()
  companion = T
  instance.method1()
  companion.method2()
}

要像这样使用:

class Yyy extends Xxx[Aaa] {}

我该如何实现?如果我可以使用新的Scala Reflection API,那就更好了。提前谢谢!

1 个答案:

答案 0 :(得分:0)

目前我正在使用一种解决方案,避免使用泛型来获取伴随类型:

abstract class Xxx[T <: NClass[T], O <: NCompanion[T]](implicit tag: TypeTag[T]) {
  def getInstance(): T
  def getCompanion(): O

  val classOfT = typeTag[T].mirror.runtimeClass(typeOf[T])
  val className = classOfT.getName
  println(s"$className")
  val t = getInstance()
  val manager = getCompanion()
}

用法:

class Yyy extends Xxx[Aaa, Aaa.type] {
  override def getInstance: Aaa = {
    return new Aaa()
  }

  override def getCompanion: Aaa.type = {
    return Aaa
  }
}