Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector of Any to Shapeless HList

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

like image 413
user2780187 Avatar asked Mar 18 '23 19:03

user2780187


1 Answers

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.

like image 123
Travis Brown Avatar answered Mar 27 '23 23:03

Travis Brown