简体   繁体   English

Scala通用this.type

[英]Scala generics this.type

I'm trying to create a generic trait which has a method that returns an instance of the class itself. 我正在尝试创建一个通用trait,它有一个返回类本身实例的方法。 For example: 例如:

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

Without explicit return type: 没有显式返回类型:

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

This fails compilation because the return value of the implemented withData is SomeImpl but the expected return type based on the trait's method declaration is SomeImpl.this.type . 这会导致编译失败,因为实现的withData的返回值是SomeImpl但基于trait方法声明的预期返回类型是SomeImpl.this.type

Does anyone know how I need to change the return type of the trait method declaration so this will work? 有谁知道我需要如何更改特征方法声明的返回类型,以便这可以工作? The more general use case I have is a way to expose a case class' copy method through a generic trait it extends. 我有一个更通用的用例是通过它扩展的泛型特征公开case类的copy方法。 I know I may not be articulating this clearly, let me know if I should clarify anything. 我知道我可能不清楚这一点,让我知道我是否应该澄清任何事情。

Using Scala 2.10.0 使用Scala 2.10.0

You can solve it by parameterizing the trait with type type of class you're mixing into: 您可以通过使用要混合的类的类型类型参数化特征来解决此问题:

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

this.type is a singleton type - the type of one specific instantiated SomeGenericTrait . this.type是一个单例类型 - 一个特定实例化SomeGenericTrait的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM