繁体   English   中英

如何表达更高种类的类型的约束

[英]How to express type constraints for higher kinded type

我正在尝试创建一些特征的列表,这些特征使用CRTP通过类型进行参数化,并且无法弄清楚如何表达类型约束。 这里是一些示例代码,说明了此问题:

trait A[X] {
  def x: X
}

trait B[Y <: A[Y]] {
  def y(i: Int): Y
}

case class C(i: Int) extends A[C] {
  def x = C(i)
}

case class D(i: Int) extends A[D] {
  def x = D(i)
}

case class E() extends B[C] {
  def y(i: Int) = C(i)
}

case class F() extends B[D] {
  def y(i: Int) = D(i)
}

object Program extends App {
  def emptyList[X[_ <: Z forSome { type Z <: A[Z] } ]]() = collection.mutable.ListBuffer.empty[X[_]]

  val myList = emptyList[B]()
  myList += E()
  myList += F()

  println(myList.map(_.y(2).x))
}

所以在这里我试图创建一个符合B特性的对象列表。 但是,此代码将无法编译,并出现以下错误:

类型参数(B)的种类与类型参数(类型X)的预期种类不符。 B的类型参数与X的预期参数不匹配:Y类型的边界>:没什么<:A [Y]严格于类型_的声明边界>:没什么<:Z forSome {类型Z <:A [Z]} val myList = emptyList [B]()

在我看来, _ <: Z forSome { type Z <: A[Z] }确实至少与Y <: A[Y]一样严格,但也许我缺少了一些东西。

因此,问题是-正确处理B的EmptyList函数上的约束应该是什么?

经过一番尝试和错误后,我开始使用它。 注意:编译器告诉我们A [+ X]和B [+ Y]中的类型参数必须是协变的。

trait A[+X] {
  def x: X
}

trait B[+Y <: A[Y]] {
  def y(i: Int): Y
}

case class C(i: Int) extends A[C] {
  def x = C(i)
}

case class D(i: Int) extends A[D] {
  def x = D(i)
}

case class E() extends B[C] {
  def y(i: Int) = C(i)
}

case class F() extends B[D] {
  def y(i: Int) = D(i)
}


object Test extends App {
  def emptyList[X[Y <: A[Y]]] = collection.mutable.ListBuffer.empty[X[Y forSome {type Y <: A[Y]} ]]

  val myList = emptyList[B]
  myList += E()
  myList += F()

  println(myList.map(_.y(2).x))
}

暂无
暂无

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

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