简体   繁体   中英

Shapeless lenses usage with a string definition

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM