使用Scala抽象类型奇怪地重复出现模板模式约束

时间:2016-05-26 20:55:09

标签: scala crtp abstract-type

我有一个我无法弄清楚的Scala编译器错误拼图。由于此处未给出的原因,我需要使用curiously recurring template pattern声明我的类。我的一些类需要包含其他类作为参数。例如,我的代码的精简版本如下所示:

.uib-tab {
margin: 0px;
padding: 0px;
}

.uib-tabset {
margin: 0px;
padding: 0px;
}

以上工作正常。现在我想从每个-ed到每个-ed添加一个抽象类型:

trait Container[C <: Container[C]] {
  def stuff: C
}

trait Aggregation {
  def fill(x: Double): Unit
}

class Counted extends Container[Counted] {
  def stuff = this
}

class Counting extends Container[Counting] with Aggregation {
  def stuff = this
  def fill(x: Double) { }
}

class Binned[V <: Container[V]](v: V) extends Container[Binned[V]] {
  def stuff = this
  def substuff = v
}

class Binning[V <: Container[V] with Aggregation](v: V) extends Container[Binning[V]] with Aggregation {
  def stuff = this
  def substuff = v
  def fill(x: Double) { }
}

并且编译器有勇气告诉我

trait Container[C <: Container[C]] {
  type Ed <: Container[Ed]
  def stuff: C
}

trait Aggregation {
  def fill(x: Double): Unit
}

class Counted extends Container[Counted] {
  type Ed = Counted
  def stuff = this
}

class Counting extends Container[Counting] with Aggregation {
  type Ed = Counted
  def stuff = this
  def fill(x: Double) { }
}

class Binned[V <: Container[V]](v: V) extends Container[Binned[V]] {
  type Ed = Binned[V]
  def stuff = this
  def substuff = v
}

class Binning[V <: Container[V] with Aggregation](v: V) extends Container[Binning[V]] with Aggregation {
  type Ed = Binned[V#Ed]
  def stuff = this
  def substuff = v
  def fill(x: Double) { }
}

所有<console>:34: error: type arguments [V#Ed] do not conform to class Binned's type parameter bounds [V <: Container[V]] type Ed = Binned[V#Ed] Ed显然为<: Container[Ed]

严格来说,Containers只需要输入Ed,如果我将其移到那里,我会收到同样的错误。

有人知道如何表达我对编译器的意图吗?

1 个答案:

答案 0 :(得分:1)

class Binning[V <: Container[V] with Aggregation](val v: V) extends Container[Binning[V]] with Aggregation {
  type Ed = Binned[v.Ed]
  def stuff = this
  def substuff = v
  def fill(x: Double) { }
}

的工作原理。但在我看来,你的版本也应该编译。