包含HList中元素的类型类?

时间:2017-02-04 17:26:55

标签: scala shapeless

我正在尝试定义类型类,以使HList pom.xml包含特定类型src/

L

当然由于A而无法编译。

是否存在这种“等效类型”类型类?

一旦有效,我希望编译以下内容:

trait Contains[A] { type Out } object Contains { type Aux[A, O] = Contains[A] { type Out = O } def contains[L <: HList, A] (implicit ev: Contains.Aux[L, A]) = ev implicit def containsInt[H, L <: HList, A] (implicit ev: H == A): Contains.Aux[H :: L, A] = new Contains[H :: L] { type Out = A } } 因为HList中有ev: H == A

然而,由于输入HList中没有implicitly[Contains.Aux[Int :: HNil, Int]],我希望Int不能编译。

1 个答案:

答案 0 :(得分:3)

您正在寻找shapeless.ops.hlist.Selector

使用Selector,您的示例就像这样,

scala> import shapeless._, ops.hlist._
import shapeless._
import ops.hlist._

scala> Selector[Char :: HNil, Char]
res0: shapeless.ops.hlist.Selector[shapeless.::[Char,shapeless.HNil],Char] = shapeless.ops.hlist$Selector$$anon$37@20eebe9c

scala> Selector[Int :: Char :: HNil, Char]
res1: shapeless.ops.hlist.Selector[shapeless.::[Int,shapeless.::[Char,shapeless.HNil]],Char] = shapeless.ops.hlist$Selector$$anon$38@10cf3c87

scala> Selector[Int :: HNil, Int]
res2: shapeless.ops.hlist.Selector[shapeless.::[Int,shapeless.HNil],Int] = shapeless.ops.hlist$Selector$$anon$37@79d8c266

scala> Selector[Boolean :: Char :: HNil, Int]
<console>:18: error: Implicit not found: shapeless.Ops.Selector[shapeless.::[Boolean,shapeless.::[Char,shapeless.HNil]], Int]. You requested an element of type Int, but there is none in the HList shapeless.::[Boolean,shapeless.::[Char,shapeless.HNil]].
       Selector[Boolean :: Char :: HNil, Int]
               ^

scala> Selector[Boolean :: Char :: HNil, Char]
res4: shapeless.ops.hlist.Selector[shapeless.::[Boolean,shapeless.::[Char,shapeless.HNil]],Char] = shapeless.ops.hlist$Selector$$anon$38@bf88c94

scala> Selector[Boolean :: Int :: Char :: HNil, Char]
res5: shapeless.ops.hlist.Selector[shapeless.::[Boolean,shapeless.::[Int,shapeless.::[Char,shapeless.HNil]]],Char] = shapeless.ops.hlist$Selector$$anon$38@653f47f

scala> Selector[Int :: HNil, HNil]
<console>:18: error: Implicit not found: shapeless.Ops.Selector[shapeless.::[Int,shapeless.HNil], shapeless.HNil]. You requested an element of type shapeless.HNil, but there is none in the HList shapeless.::[Int,shapeless.HNil].
       Selector[Int :: HNil, HNil]
               ^