Vector of Any to Shapeless HList

302 views Asked by At

Is there a way to convert a vector of type Any to Shapeless HList (productelement)

val frame = Vector(Vector(1,"a","b",false),Vector(2,"y","z",false),Vector(3,"p","q",true))

frame.map(_.hlisted) or frame.map(_.productElements)

I am attempting to convert to the following structure

List[Int :: String :: String :: Boolean :: HNil](1 :: a :: b :: false :: HNil, 2 :: y :: z :: false :: HNil, 3 :: p :: q :: true :: HNil)

Based on Shapless Migration guide, it's possible with Typed Tuples

https://github.com/milessabin/shapeless/wiki/Migration-guide:-shapeless-1.2.4-to-2.0.0#productelements-is-the-new-name-for-hlisted

import shapeless._
import syntax.std.product._  // New import

scala> (23, "foo", true).productElements // was '.hlisted'
res0: Int :: String :: HNil = 23 :: foo :: true :: HNil

Is this possible with untyped Vectors or perhaps a vector -> Typed Tuples -> HList ?

Thanks in advance

1

There are 1 answers

1
Travis Brown On BEST ANSWER

Yes, it's possible, but you have to specify the types, and since this is a cast that can fail at runtime, you'll get the results wrapped in Option:

import shapeless._, syntax.std.traversable._

val hlists = frame.map(_.toHList[Int :: String :: String :: Boolean :: HNil])

Now hlists has type Vector[Option[Int :: String :: String :: Boolean :: HNil]], and in this case specifically all of the conversions are successful, so they're all wrapped in Some.