如何将 Const 仿函数的 HList 转换为 Seq?

How to turn an HList of Const functors into a Seq?

我有一个像这样的高级数据类型

case class Foo[F[_] : Functor](a: F[Int], b: F[Double])

和一个用某种字符串标记每个成员的值(例如 CSV 列的名称):

val colNames = new Foo[Const[String, *]](a = Const("AAA"), b = Const("BBB"))

现在我需要以某种方式将 colNames 转换为 Seq[String]。当然有标准的 scala 方法 productIterator,但它只有 returns Iterator[Any].

使用 shapeless 我可以获得一个 HList,其中列表中的每个类型都是 Const[String, _]:

val colNamesHlist: Const[String, _] :: Const[String, _] :: HNil = Generic[Foo[Const[String, *]]].to(colNames)

但是我怎样才能把它变成一个常规列表呢?

我也对任何不涉及 shapeless 的想法持开放态度,尽管我认为这是无法避免的。

你可以这样做:

val colNameList: List[String] =
  Generic[Foo[Const[String, *]]]
    .to(colNames)
    .toList[Const[String, A] forSome { type A }]
    .map(_.getConst)

可以看到代码运行 here.