Home > Software engineering >  How to turn an HList of Const functors into a Seq?
How to turn an HList of Const functors into a Seq?

Time:02-10

I have a higher-kinded data type like this

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

and a value that labels every member with some kind of string (the name of a CSV column for example):

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

Now I need to somehow convert colNames into a Seq[String]. There is the standard scala method productIterator of course, but it only returns Iterator[Any].

Using shapeless I can get an HList where every type in the list is Const[String, _]:

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

But how can I turn this into a regular list?

I am also open to any ideas not involving shapeless, though I don't think it can be avoided.

CodePudding user response:

You may do this:

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

You can see the code running here.

  • Related