gpt4 book ai didi

scala - 如何将通用 HList 转换为列表

转载 作者:行者123 更新时间:2023-12-04 07:37:43 26 4
gpt4 key购买 nike

我有这些:

trait A[T]
class X
class Y

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

参数 hmethod将始终是 A[T] 的 HList,例如 new A[X]::new A[Y]::HNil。

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

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

最佳答案

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

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

现在您可以编写以下内容:
val someAs = new A[Int] {} :: new A[String] {} :: HNil

进而:
scala> B.method(someAs)
res0: List[A[_]] = List($anon$1@5dd508ef, $anon$2@4d3db309)

几乎所有对 HList 的操作将需要这种隐性证据。

关于scala - 如何将通用 HList 转换为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25404968/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com