-->

Shapeless lenses usage with a string definition

2019-08-20 22:25发布

问题:

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?