scala HList Ops -类型类是如何执行的?

jc3wubiy  于 5个月前  发布在  Scala
关注(0)|答案(1)|浏览(61)

有人能解释一下为什么这段代码编译和工作起来很有魅力吗?

val a = true :: Some(5) :: true :: HNil
a.select[Some[Int]]                                // Some(5)

字符串
但这个失败了

def foo[HL <: HList](a: HL): Some[Int] = {
  a.select[Some[Int]]                              // fails
}
Implicit not found: shapeless.Ops.Selector[tp, Some[Int]]. You requested an element of type Some[Int], but there is none in the HList tp.
a.select[Some[Int]]

的数据
我不想传递一个示例。
我也试过:

type tp = Boolean :: Option[Int] :: Boolean :: HNil
def foo(a: tp): Some[Int] = a.select[Some[Int]]       // fails
foo(a)


但它失败了,并传递了一个信息:

Implicit not found: shapeless.Ops.Selector[tp, Some[Int]]. You requested an element of type Some[Int], but there is none in the HList tp.
a.select[Some[Int]]

xkrw2x1b

xkrw2x1b1#

this

def foo[HL <: HList](a: HL)
                    (implicit sel: ops.hlist.Selector[HL, Some[Int]]): Some[Int] = {
  a.select[Some[Int]]                       
}

字符串
select的完整签名是

def select[U](implicit selector: hlist.Selector[HL,U]): U


这里有一个隐式参数selector,因此您必须提供一个。

相关问题