简体   繁体   English

实现 trait 的类的类型参数而忽略 trait 参数

[英]Type parameter for classes implementing trait disregarding trait parameters

I have a trait with type parameters and it has a list containing instances of another classes implementing this trait.我有一个带有类型参数的特征,它有一个列表,其中包含实现此特征的另一个类的实例。 I don't care about type paramaters of those instances, so I try to define a type that would allow any subclass implementing the trait with whatever type parameters.我不关心这些实例的类型参数,所以我尝试定义一个类型,允许任何子类使用任何类型参数实现特征。

trait Synchronizable[A,B] {
  type S <: Synchronizable[_,_]

  val slaves: MutableList[S]

  def synchronizeWith(q: S) = {
    if (!slaves.contains(q)) slaves += q
  }

}

But it won't compile due to some particular instance doesn't conform to this type definition.但由于某些特定实例不符合此类型定义,因此无法编译。

[error]  found   : TwoBuffers.this.faster.type (with underlying type model.collection.SynchronizableTimeSeriesBuffer[someCaseClass ,Option[Any]])
[error]  required: TwoBuffers.this.slower.S
[error]     slower.synchronizeWith(faster)

Firstly, it's not clear from your question how you are using this trait.首先,从你的问题中不清楚你是如何使用这个特性的。 I think you might want something like this:我想你可能想要这样的东西:

trait Synchronizable[A,B] {
  type S = Synchronizable[_, _] // Note =, not <:

  val slaves = MutableList.empty[S] // Create list in trait.

  def synchronizeWith(q: S) = {
    if (!slaves.contains(q)) slaves += q
  }
}

Alternatively, if you really need to use the type S <: Synchronizable[_, _] declaration, then you will need to override the type statement in a sub-class.或者,如果您确实需要使用type S <: Synchronizable[_, _]声明,那么您将需要覆盖子类中的type语句。 For example:例如:

trait Synchronizable[A,B] {
  type S <: Synchronizable[_, _]

  val slaves = MutableList.empty[S] // Create list in trait.

  def synchronizeWith(q: S) = {
    if (!slaves.contains(q)) slaves += q
  }
}

class SomeClass[A, B]
extends Synchronizable[A, B] {
  override type S = SomeClass[_, _]
}

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

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