Simon
Simon

Reputation: 6490

Shapeless: is there a way to get Hlist type from a case class or a tuple

I'm totally new to shapeless. I create a case class from a list as following:

val list = Seq(Some(1), Some(1.0), ...)
val y =
  list
    .toHList[Option[Int]::Option[Double]::Option[Int]::Option[Double]::Option[Double]::Option[Double]::Option[Double]::Option[Double]::Option[Double]::Option[Double]::Option[Double]::Option[Double]::Option[Double]::Option[Double]::HNil]

val z = y.get.tupled
val aa = YieldVariables.tupled(z)

It works well but I'm wondering if there is a way not to write all these types in the toHList[Here] part.

So I want to know if something like list.toHList[find the type yourself] or list.getTypesForHlist or yet MyCaseClass.getTypesForHlist that results to Option[Int]::Option[Double]... exists.

Upvotes: 4

Views: 1525

Answers (1)

OlivierBlanvillain
OlivierBlanvillain

Reputation: 7768

For case classes (and tuples, these are also case classes!), use Generic:

case class A(i: Int, s: String)
shapeless.Generic[A].to(A(1, "")) // Int :: String :: HNil

This is not possible to do on Seq. Indeed, as soon as you've called the constructor, the information about how many element you passed to that constructor is gone from a type perspective. Shapeless also has SingletonProductArgs: a macro for a varargs like syntax that returns an HList instead of a Seq.

Upvotes: 5

Related Questions