How should I extract the value of a field of a case class from a given String value representing the field.
For example:
case class Person(name: String, age: Int)
val a = Person("test",10)
Now here given a string name
or age
i want to extract the value from variable a
. How do i do this? I know this can be done using reflection but I am not exactly sure how?
What you're looking for can be achieve using Shapeless lenses. This will also put the constraint that a field actually exists on a case class at compile time rather than run time:
Yields:
If you try to extract a non existing field, you get a compile time error, which is a much stronger guarantee:
Compiler yells:
don't know exactly what you had in mind, but a
match
statement would do, it is not very generic or extensible with regards changes to thePerson
case class, but it does meet your basic requirements of not using reflection:UPDATE as per comment:
I think it can do by convert case class to Map, then get field by name
Usage