从 LabelledGeneric 实例中提取标签值 [英] Extract label values from a LabelledGeneric instance

查看:42
本文介绍了从 LabelledGeneric 实例中提取标签值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下示例:

import shapeless._

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

现在,labl 的类型是(美化的)

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.

我正在寻找的是一种从 labl 到类似

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.

这可能吗?我可以使用宏,但我觉得我最终会在 shapeless 中重写与 GenericMacros 对象非常相似的东西,所以我想知道我是否可以直接利用它.

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.

推荐答案

您可以通过 shapeless.ops.record.Keys 获取记录的键(如 Symbols)代码>.

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

这个

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))

结果

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

这篇关于从 LabelledGeneric 实例中提取标签值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆