Scala通用this.type

ggr*_*ner 14 generics scala

我正在尝试创建一个通用trait,它有一个返回类本身实例的方法.例如:

trait SomeGenericTrait[T]{
   def withData(newData : Seq[T]) : this.type
}

case class SomeImpl(data : Seq[Int]) extends SomeGenericTrait[Int] {
   override def withData(newData : Seq[Int]) : SomeImpl = copy(data = newData)
}

error: overriding method withData in trait SomeGenericTrait of type(newData: Seq[Int])SomeImpl.this.type; method withData has incompatible type
Run Code Online (Sandbox Code Playgroud)

没有显式返回类型:

case class SomeImpl(data : Seq[Int]) extends SomeGenericTrait[Int] {
   override def withData(newData : Seq[Int]) = copy(data = newData)
}

error: type mismatch;
 found   : SomeImpl
 required: SomeImpl.this.type
Run Code Online (Sandbox Code Playgroud)

这会导致编译失败,因为已实现的返回值withDataSomeImpl基于特征的方法声明的预期返回类型SomeImpl.this.type.

有谁知道我需要如何更改特征方法声明的返回类型,以便这可以工作?我有一个更通用的用例是copy通过它扩展的泛型特征公开case类的方法.我知道我可能不清楚这一点,让我知道我是否应该澄清任何事情.

使用Scala 2.10.0

Knu*_*daa 12

您可以通过使用要混合的类的类型类型参数化特征来解决此问题:

trait SomeGenericTrait[T, X] {
  def withData(newData: Seq[T]): X
}

case class SomeImpl(data: Seq[Int]) extends SomeGenericTrait[Int, SomeImpl] {
  override def withData(newData: Seq[Int]): SomeImpl = copy(data = newData)
}
Run Code Online (Sandbox Code Playgroud)

this.type是一个单例类型 - 一个特定实例化的类型SomeGenericTrait.