Scala self-type and generic class

我只是一个虾纸丫 提交于 2019-12-11 16:25:05

问题


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

In the example above, is there a way so that we don't have to repeat the type in the self-typed "bar" trait? Therefore we could declare ConcreteFooBar like this:

object ConcreteFooBar extends Bar[Int] with Foo {}

回答1:


You can use an abstract type instead of a type parameter for Foo, like this:

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


来源:https://stackoverflow.com/questions/47554414/scala-self-type-and-generic-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!