我想以某种方式在编译时获取val中的case类的字段的名称(可能是单例类型的字符串或符号?)。
类似于以下内容:
import shapeless._
case class MyClass(field1: String, field2: Int)
val field1Lens = lens[MyClass] >> 'field1
// val name = field1Lens.name // it should be "field1", aka 'field1.name
我没有必要使用镜头,任何有效的技术都很好(有些东西 LabelledGeneric
?)。我想有一些东西,我可以获得案例类字段的名称,而无需单独指定。这样,如果我重构的名称 field1
班上的成员, name
相应地改变。
当然以下不起作用,因为宏在编译时不知道符号的名称:
val name = 'field1
val field1Lens = lens[MyClass] >> name // can't possibly work
我试过了 lens[MyClass] >> name.narrow
但它也不起作用
这就是我目前正在做的事情,当然我不喜欢它:
// If I change the name of the field, compilation fails
// and I'm forced to check this line of code so I can change the string in the line below
protected val fieldNameCheck = lens[X].someField
val someField = "someField"
编辑:好的,我看了看 加布里埃莱的问题,并通过使用 Keys
我能够获得包含记录(标记)键的HList。
我需要的是获得一个特定字段,而不是包含所有字段的列表。
我正在尝试使用 select
获得一个特定的密钥,但到目前为止我没有成功
import shapeless._
import shapeless.syntax.singleton._
import shapeless.ops.record._
case class Foo(bar: String, baz: Boolean)
val labl = LabelledGeneric[Foo]
val keys = Keys[labl.Repr].apply
// the following doesn't work
// val bar = 'bar.narrow
// keys.select[bar.type]
// keys.get('bar)