加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 如何表达更高类型的类型约束

发布时间:2020-12-16 08:53:51 所属栏目:安全 来源:网络整理
导读:我正在尝试创建一个使用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)
我正在尝试创建一个使用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特征的对象列表.但是,此代码将无法编译,并给出以下错误:

kinds of the type arguments (B) do not conform to the expected kinds of the type parameters (type X). B’s type parameters do not match type X’s expected parameters: type Y’s bounds >: Nothing <: A[Y] are stricter than type _’s declared bounds >: Nothing <: Z forSome { type Z <: A[Z] } val myList = emptyList[B] ()

对我而言,似乎_<:Z forSome {type Z<:[[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))
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读