2017-01-07 53 views
2

使用Generic#to,我可以得到一個case classHList表示:通用#到,但帶有字段名稱?

import shapeless._ 
case class F(x: Int, y: String) 

scala> Generic[F].to(F(1, "foo")) 
res1: shapeless.::[Int,shapeless.::[String,shapeless.HNil]] = 
    1 :: foo :: HNil 

不過,我想獲得以下方面的代表:

("x", 1) :: ("y", "foo") :: HNil

換句話說,而不是隻F實例字段的值,我想要獲取字段名稱,即xy

我怎樣才能得到這種表示?

回答

3

您正在尋找LabelledGeneric

爲了打印的字段,就可以再使用Fields型類(從ops.record封裝),其可與.fields被調用,如果你也導入record包。

這裏有一個完整的例子

import shapeless._, record._, ops.record._ 
case class F(x: Int, y: String)  

scala> LabelledGeneric[F].to(F(1, "foo")).fields 
res1: shapeless.::[(Symbol with shapeless.tag.Tagged[String("x")], Int),shapeless.::[(Symbol with shapeless.tag.Tagged[String("y")], String),shapeless.HNil]] = ('x,1) :: ('y,foo) :: HNil 

如果你也想鍵轉換爲String

object keysToString extends Poly1 { 
    implicit def keyToName[A, B] = at[(Symbol with A, B)] { case (k, v) => (k.name, v) } 
} 

scala> LabelledGeneric[F].to(F(1, "foo")).fields.map(keysToString) 
res2: shapeless.::[(String, Int),shapeless.::[(String, String),shapeless.HNil]] = (x,1) :: (y,foo) :: HNil 
相關問題