gattaccio
gattaccio

Reputation: 19

shapeless record get value by Symbol

Trying to extract a field value but it doesn't work when called with a Symbol

case class Dog(name: String, age: Int)
val dog = Dog("rocky", 5)
val repr = LabelledGeneric[Dog].to(dog)
val sy = 'name
repr.get(sy)

but works if I do

repr.get('name)

Upvotes: 1

Views: 502

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

The first example works because the macro expansion actually converts the Symbol instance to a Witness instance (using Witness.mkWitness) which is actually what repr.get is expecting.

In order to make this work we need to create an instance of the Witness we want explicitly:

import shapeless.{LabelledGeneric, Witness}

case class Dog(name: String, age: Int)
val dog = Dog("rocky", 5)

val repr = LabelledGeneric[Dog].to(dog)
val nameWitn = Witness('name)
repr.get(nameWitn)

Upvotes: 1

Related Questions