Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

scala - Extract label values from a LabelledGeneric instance

Consider the following example:

import shapeless._

case class Foo(bar: String, baz: Boolean)
val labl = LabelledGeneric[Foo]

Now, the type of labl is (prettified)

LabelledGeneric[Foo] {
  type Repr =
    FieldType[Symbol @@ String("bar"), String] ::
    FieldType[Symbol @@ String("baz"), Boolean] ::
    HNil
}

which already conveys the information I need, i.e. the names of the case class fields.

What I'm looking for is a way to go from labl to something along the lines of

"bar" :: "baz" :: HNil

i.e. materializing the information contained in the singleton types into a value.

Is this possible? I could use a macro, but I feel like I would end up rewriting something very similar to the GenericMacros object in shapeless, so I'm wondering whether I can leverage it directly.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can obtain the keys of the record (as Symbols) via shapeless.ops.record.Keys.

This

import shapeless._
import shapeless.ops.record._

case class Foo(bar: String, baz: Boolean)
val labl = LabelledGeneric[Foo]
val keys = Keys[labl.Repr].apply
println(keys)
println(keys.toList.map(_.name))

results in

'bar :: 'baz :: HNil
List(bar, baz) : List(String)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...