Shapeless lenses usage with a string definition

孤街浪徒 提交于 2019-12-13 20:28:16

问题


I would like use shapeless lenses to access value of the case class field by a String definition.

I know this code works.

case class Test(id: String, calc: Long)
val instance = Test("123232", 3434L)

val lens = lens[Test] >> 'id

val valueOfFieldId = lens.get(instance)

But what I am trying to do is:

 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.

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

Is it possible to get the value of case class field with a String definition?

Thanks.


回答1:


You are supposed to use Symbol ('id) here rather than String ("id").

Creating Symbol from String

Symbol(fieldName)

is runtime operation and Shapeless operates in compile time.

Why can't you use symbols?



来源:https://stackoverflow.com/questions/50418767/shapeless-lenses-usage-with-a-string-definition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!