Scala自我类型和泛型类

时间:2017-11-29 13:51:32

标签: scala generics types self-type

abstract class Bar[M] {
  def print(t: M): Unit = {
    println(s"Bar: ${t.getClass()}")
  }
}

trait Foo[M] {
  this: Bar[M] =>
  def print2(t: M): Unit = {
    println(s"Foo: ${t.getClass()}")
  }
}

object ConcreteBar extends Bar[Int] with Foo[Int] {}
object ConcreteFooBar extends Bar[Int] with Foo[Int] {}

object Test {
  def main(args: Array[String]): Unit = {
    ConcreteBar.print(1)
    ConcreteFooBar.print2(1)
  }

在上面的示例中,是否有一种方法可以让我们不必在自键型" bar"中重复此类型。特征? 因此我们可以像这样声明ConcreteFooBar:

object ConcreteFooBar extends Bar[Int] with Foo {}

1 个答案:

答案 0 :(得分:0)

您可以使用抽象类型而不是Foo的类型参数,如下所示:

abstract class Bar[M] {
  type Base = M
  def print(t: M): Unit = {
    println(s"Bar: ${t.getClass()}")
  }
}

trait Foo {
  type Base
  def print2(t: Base): Unit = {
    println(s"Foo: ${t.getClass()}")
  }
}