协变类型出现在HList中的不变位置

时间:2017-08-03 13:01:49

标签: scala shapeless scala-generics

我试图定义一个类型安全的异构列表,它对元素的类型有限制,强制元素之间的层次结构(例如类型A不能出现在类型B之后)。当试图将我的结构转换为无形状时会发生麻烦。 HList。

以下是我为我的类型定义特征的方法:

sealed trait Hierarchy {
  type HListType <: HList
  def toHList : HListType

  def toCaseClass[C](implicit gen: Generic[C]{type Repr >: HListType}) = gen.from(toHList)
}

sealed trait <::[+H <: ElType[_], +T <: Hierarchy] extends Hierarchy {

  override type HListType = H :: tail.HListType

  val head: H
  val tail: T

  override def toHList: HListType = head :: tail.toHList

}

我收到以下错误:

Hierarchy.scala:26: covariant type H occurs in invariant position in type shapeless.::[H,<::.this.tail.HListType] of type HListType

这非常令人费解,因为shapeless.::的定义定义了两个类型参数都是协变的。

我正在使用scala 2.11.11和无形2.3.2。有没有办法解决这个错误?

1 个答案:

答案 0 :(得分:0)

来自Scala规范:

  

类型别名的右侧始终处于不变位置。

所以问题不是来自HList的定义,而是来自我在类型别名中使用type参数的事实。

我将定义更改为

sealed trait <::[+H, +T <: Hierarchy] extends Hierarchy {

  type H_ <: ElType[H]

  override type HListType = H_ :: tail.HListType

  val head: H_
  val tail: T

  override def toHList: HListType = head :: tail.toHList

}

问题就消失了。

相关问题