在特征之间共享通用

Min*_*Ant 5 generics types scala

我有两个特点

trait Base[A]

trait SometimesUsedWithBase[A] {
    this: Base[A] =>
}
Run Code Online (Sandbox Code Playgroud)

然后我在课堂上使用它们

class StringThing extends Base[String] with SometimesUsedWithBase[String]
Run Code Online (Sandbox Code Playgroud)

如果我不必定义CertainUsedWithBase的类型,那将是很好的,而是它以某种方式理解它使用Base中定义的类型,使它看起来像:

class StringThing extends Base[String] with SometimesUsedWithBase
Run Code Online (Sandbox Code Playgroud)

这可能吗?

小智 7

你应该可以做这样的事情.

trait Base[A] {
  type BaseType = A
}

trait SometimesUsedWithBase {
  this: Base[_] =>
  def someFunction: BaseType
}

class StringThing extends Base[String] with SometimesUsedWithBase {
  def someFunction: String = ""
}
Run Code Online (Sandbox Code Playgroud)