【问题标题】:How to convert a generic HList to a List如何将通用 HList 转换为 List
【发布时间】:2014-08-20 12:39:25
【问题描述】:

我有这些:

trait A[T]
class X
class Y

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

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

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

由于 trait HList 没有 toList 方法(),我如何使用通用代码获得此功能?

【问题讨论】:

    标签: scala shapeless


    【解决方案1】:

    编译器错误应该告诉您需要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 上的几乎所有操作都需要这种隐含证据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-10
      • 1970-01-01
      • 2010-10-08
      • 2020-11-27
      相关资源
      最近更新 更多