如何将通用HList转换为List

dav*_*rez 7 scala shapeless

我有这些:

trait A[T]
class X
class Y

object B {
   def method[H :< HList](h: H) = h.toList[A[_]]
}
Run Code Online (Sandbox Code Playgroud)

参数hmethod永远是A [T]的HList,如新A [X] ::新A [Y] ::高抗扰度逻辑.

我想将HList转换为List [A [_]].

我怎么能用通用代码得到这个,因为trait HList没有toList方法()?

Tra*_*own 8

编译器错误应告诉您有关想要隐式值类型的信息shapeless.ops.hlist.ToList[H, A[_]].您可以通过向方法签名添加隐式参数列表来提供其中一个:

object B {
  def method[H <: HList](h: H)(implicit ev: ToList[H, A[_]]) = h.toList[A[_]]
}
Run Code Online (Sandbox Code Playgroud)

现在您可以编写以下内容:

val someAs = new A[Int] {} :: new A[String] {} :: HNil
Run Code Online (Sandbox Code Playgroud)

然后:

scala> B.method(someAs)
res0: List[A[_]] = List($anon$1@5dd508ef, $anon$2@4d3db309)
Run Code Online (Sandbox Code Playgroud)

几乎所有关于HList遗嘱的操作都需要这种隐含的证据.