在mixin上推断类型参数

Ara*_*ian 5 scala

假设我有一些特征:

trait A[T] { def foo: T }
Run Code Online (Sandbox Code Playgroud)

扩展它的类:

class B[T](t: T) extends A[T] { def foo = t }
Run Code Online (Sandbox Code Playgroud)

和父特征的一个子特征:

trait C[T] extends A[T]
Run Code Online (Sandbox Code Playgroud)

我想将C与B混合使用。

val foo = new B("foo") with C[String]
Run Code Online (Sandbox Code Playgroud)

这可以正常工作,但是我不希望再次指定type参数,因为B已经是A [String]类型。但是,我知道Scala不支持以下功能:

val foo = new B("foo") with C
Run Code Online (Sandbox Code Playgroud)

我的问题是类型系统中还有其他机制可以支持在混合C时不必指定类型参数。我当时想的是:

trait C {
  self: A[T] => ...
}
Run Code Online (Sandbox Code Playgroud)

有人会认为这种事情会解决将C混入其中的问题。但是,它不是有效的Scala。就像是:

trait C {
  type T
  self: A[T] =>
}
Run Code Online (Sandbox Code Playgroud)

也不起作用。

Sum*_*uma 1

您可以使用抽象类型来做到这一点:

  trait A {
    type AT
    def foo: AT
  }

  class B[T](t: T) extends A {
    type AT = T 
    def foo = t
  }

  trait C extends A

  val foo = new B("foo") with C
Run Code Online (Sandbox Code Playgroud)

定义有点冗长,但T满足了您不必再次键入的要求。