无形:尝试按类型限制HList元素

sth*_*elo 7 scala constraints hlist shapeless

问题1 - 基本LUBConstraints

我第一次尝试使用现有的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)
}
Run Code Online (Sandbox Code Playgroud)

任何帮助赞赏.

问题2 - 使用Coproduct自己的约束 (分成单独的问题:无形:使用Coproduct自己的HList约束)

问题3 - 按参数类型限制案例类 (拆分为单独的问题:无形:限制案例类类型)

Tra*_*own 6

该值的推断类型HNil将是单例类型HNil.type,它是 的适当子类型HNil。因为诸如此类的类型类LUBConstraint是不变的,所以HNil如果您要求HNil.type.

一些关于更改 的定义的讨论HNil以便这可以工作,但这并非微不足道,并且不清楚更改的所有含义都是可取的。同时,您可以写入HNil: HNil以向上转换该值。