Scala 自类型和泛型 class

Scala self-type and generic class

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 {}

您可以为 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()}")
  }
}