字符串定义可用于无形镜片 [英] Shapeless lenses usage with a string definition
问题描述
我想使用无形透镜来通过String定义访问案例类字段的值.
I would like use shapeless lenses to access value of the case class field by a String definition.
我知道这段代码有效.
case class Test(id: String, calc: Long)
val instance = Test("123232", 3434L)
val lens = lens[Test] >> 'id
val valueOfFieldId = lens.get(instance)
但是我想做的是:
val fieldName = "id"
val lens = lens[Test] >> fieldName.witness
//I typed .witness because it was expecting a witness (if I am not wrong)
val valueOfFieldId = lens.get(instance)
但是使用此代码,我得到了这个错误.
But with this code, I am getting this error.
找不到参数mkLens的隐式值:shapeless.MkFieldLens [A $ A148.this.Test,A $ A148.this.str.type] def get $$ instance $$ lll = lll;/* ### worksheet ###生成$$ end $$ */lazy val lens = lens [Test] >> str.witness
Could not find implicit value for parameter mkLens: shapeless.MkFieldLens[A$A148.this.Test,A$A148.this.str.type] def get$$instance$$lll = lll;/* ###worksheet### generated $$end$$ */ lazy val lens = lens[Test] >> str.witness
是否可以使用String定义获取case类字段的值?
Is it possible to get the value of case class field with a String definition?
谢谢.
推荐答案
您应该在这里使用Symbol
('id
)而不是String
("id"
).
You are supposed to use Symbol
('id
) here rather than String
("id"
).
从String
Symbol(fieldName)
是运行时操作,Shapeless在编译时操作.
is runtime operation and Shapeless operates in compile time.
为什么不能使用符号?
这篇关于字符串定义可用于无形镜片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!