我正在使用Shapeless 2.0,我正在尝试使用HList来验证输入 - 尽可能在编译时执行检查.
我有一个HList spec,它指定我期望的输入类型(应该在编译时检查类型),还可以包括要执行的运行时检查(例如,测试数字是偶数还是奇数).
请考虑以下规范:
trait Pred[T] { def apply(t: T): Boolean }
val IsString = new Pred[String] { def apply(s: String) = true }
val IsOddNumber = new Pred[Int] { def apply(n: Int) = n % 2 != 0 }
val IsEvenNumber = new Pred[Int] { def apply(n: Int) = n % 2 == 0 }
val spec = IsEvenNumber :: IsString :: IsString :: IsOddNumber :: HNil
Run Code Online (Sandbox Code Playgroud)
各种样本输入:
val goodInput = 4 :: "foo" :: …Run Code Online (Sandbox Code Playgroud)