在参数化特征中引用自我类型

时间:2014-04-01 03:16:05

标签: scala

我有以下问题:我希望有一个'实例' (参数化特征)和'配置',后者由实例类型参数化:

trait Kind
trait Kind1 extends Kind
trait Kind2 extends Kind

trait Instance[T <: Kind] {
  def configuration: InstanceConfiguration[Instance[_]]
}

trait InstanceConfiguration[+T <: Instance[_]] {
}

class AInstance extends Instance[Kind1] {
  override def configuration: AConfiguration = ???
}

class AConfiguration extends InstanceConfiguration[AInstance] {
}

class BInstance extends Instance[Kind1] {
  override def configuration: AConfiguration = ???
}

所以,问题是InstanceConfiguration[Instance[Kind2]]不能用作Instance[Kind1]的配置,但现在它太通用了,我想编译器在{{1}上发出错误}}

那么如何更改Instance trait中的配置定义以引用具体类型的具体InstanceConfiguration?

1 个答案:

答案 0 :(得分:2)

您需要使用F-Bounded多态性。我建议在Twitter的Scala学校阅读the section,但简而言之,Instance需要将具体类型作为类型参数:

trait Kind
trait Kind1 extends Kind
trait Kind2 extends Kind

trait Instance[A <: Instance[A, T], T <: Kind] {
  self: A =>
  def configuration: InstanceConfiguration[A]
}

trait InstanceConfiguration[+T <: Instance[_, _]] {
}

class AInstance extends Instance[AInstance, Kind1] {
  override def configuration: AConfiguration = ???
}

class AConfiguration extends InstanceConfiguration[AInstance] {
}

class BInstance extends Instance[BInstance, Kind1] {
  override def configuration: AConfiguration = ???
}