斯卡拉 – 矢量任何形状的HList

前端之家收集整理的这篇文章主要介绍了斯卡拉 – 矢量任何形状的HList前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有办法将Any类型的矢量转换为无形HList(productelement)

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

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

我试图转换为以下结构

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

基于Shapless Migration指南,可以使用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

这可能是无类型的矢量或可能是矢量 – >键入的元组 – > HList?

提前致谢

解决方法

是的,这是可能的,但您必须指定类型,并且由于这是一个可能在运行时失败的强制转换,您将获得包含在Option中的结果:

import shapeless._,Syntax.std.traversable._

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

现在hlists有类型Vector [Option [Int :: String :: String :: Boolean :: HNil]],在这种情况下,特别是所有的转换都是成​​功的,所以它们都包含在Some中.

猜你在找的Scala相关文章