这是shapeless 可以以通用 方式完成的事情,包括转换为HList。
首先 - get shapeless。然后打开依赖方法类型运行 scala(在 2.10 中默认打开):
C:\Scala\sdk\scala-2.9.2\bin>scala -Ydependent-method-types
Welcome to Scala version 2.9.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_04).
Type in expressions to have them evaluated.
Type :help for more information.
将 shapeless 添加到类路径中:
scala> :cp C:\Users\cmarsha\Downloads\shapeless_2.9.2-1.2.2.jar
Added 'C:\Users\cmarsha\Downloads\shapeless_2.9.2-1.2.2.jar'. Your new classpath is:
"C:\tibco\tibrv\8.2\lib\tibrvnative.jar;C:\Users\cmarsha\Downloads\shapeless_2.9.2-1.2.2.jar"
现在让我们玩吧!
scala> (1, 2.3, 'a, 'b', "c", true)
res0: (Int, Double, Symbol, Char, java.lang.String, Boolean) = (1,2.3,'a,b,c,true)
我们必须导入无形
scala> import shapeless._; import Tuples._; import Nat._
import shapeless._
import Tuples._
import Nat._
我们把我们的元组变成HList
scala> res0.hlisted
res2: shapeless.::[Int,shapeless.::[Double,shapeless.::[Symbol,shapeless.::[Char,shapeless.::[java.lang.String,shapeless.::[Boolean,shapeless.HNil]]]]]] = 1 :: 2.3 :: 'a :: b :: c :: true :: HNil
然后我们取前4个(注意_4是类型参数,不是方法参数)
scala> res2.take[_4]
res4: shapeless.::[Int,shapeless.::[Double,shapeless.::[Symbol,shapeless.::[Char, shapeless.HNil]]]] = 1 :: 2.3 :: 'a :: b :: HNil
现在转换回元组
scala> res4.tupled
res5: (Int, Double, Symbol, Char) = (1,2.3,'a,b)
我们可以缩短这个:
val (a, b, c, d) = sixtuple.hlisted.take[_4].tupled
//a, b, c and d would all have the correct inferred type
这当然推广到N-tuple 的第一个M 元素