问题 1 - 基本 LUB 约束
我第一次尝试使用现有的 LUBConstraints 失败,因为缺少证据(请参见下面的代码块)。任何提示为什么?空列表不是有效的多头列表吗?没有元素违反约束。
import shapeless.ops.coproduct
import shapeless.{::, :+:, Coproduct, HNil, HList}
object testLUBConstraints {
import shapeless.LUBConstraint._
// !!! see comment on question - this satisfies the implicit below!!!
// implicit val hnilLUBForLong = new LUBConstraint[HNil.type, Long] {}
def acceptLong[L <: HList : <<:[Long]#λ](l: L) = true
val validLong = acceptLong(1l :: HNil)
val validEmpty = acceptLong(HNil)
// => WHY??? Error: could not find implicit value for evidence parameter of type shapeless.LUBConstraint[shapeless.HNil.type,Long]
// MY EXPECTATION WAS: 'implicit def hnilLUB[T] = new LUBConstraint[HNil, T] {}' defined within LUBConstraint companion should provide so
// val invalid = acceptLong(1.0d :: HNil) -> fails due to missing evidence (as expected)
}
任何帮助表示赞赏。
问题 2 - 使用 Coproduct 的自身约束
(分成一个单独的问题:Shapeless: own HList constraint using Coproduct)
问题 3 - 按参数类型限制案例类别
(分成一个单独的问题:Shapeless: restricting case class types)
最佳答案
值的推断类型 HNil
将是单例类型 HNil.type
,它是 HNil
的正确子类型.因为类型类如 LUBConstraint
是不变的,HNil
的任何可用实例如果您要求 HNil.type
的实例,将不会被找到.
有some discussion更改 HNil
的定义所以这会起作用,但这不是微不足道的,而且不清楚改变的所有影响都是可取的。同时你可以写HNil: HNil
向上提升值(value)。
关于scala - Shapeless: 试图通过类型来限制 HList 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32778746/