How to list shapeless write and field access keys at runtime?

I write general code for processing lists of instances of the case class, collecting values ​​in each field, combining, and then passing it to the library.

Using formless LabelledGeneric and polymorphic functions, it looks like this:

 object toNamedSingletonListOfValues extends Poly1 { implicit def caseField[K,T] = at[FieldType[K, T]](field => { field.key -> List[T](field) }) } val generic = LabelledGeneric[MyClass] val records = listOfMyClassInstances.map(generic.to) val values = records.map(_.map(toNamedSingletonListOfValues)) // Then combining and passing 

However, I need a way to get field.key , because the library needs parameter names.

Could you offer a solution?

+7
scala record shapeless
source share
2 answers

You can access the key (which is known at compile time) as a run-time value through an instance of the Witness class:

 object toNamedSingletonListOfValues extends Poly1 { implicit def caseField[K, T](implicit wk: Witness.Aux[K]) = at[FieldType[K, T]](field => { wk.value -> List[T](field) }) } 

No need to reflect the runtime!

+11
source share

Found a dirty hack to make Poly look like this:

 import scala.reflect.runtime.universe._ object toNamedSingletonListOfValues extends Poly1 { implicit def caseField[K: TypeTag, T] = at[FieldType[K, T]] { field => (typeOf[K] match { case TypeRef(_, _, args) => args }).last.toString.drop("java.lang.String(\"".size).dropRight(2) -> List[T]() } } 

Is there a nicer solution?

0
source share

All Articles