How to generalize field names using Shapeless?

Given the case class A, I can extract its field names using Shapeless using the following snippet:

val fieldNames: List[String] = {
  import shapeless._
  import shapeless.ops.record.Keys

  val gen = LabelledGeneric[A]
  val keys = Keys[gen.Repr].apply
  keys.toList.map(_.name)
}

This works well, but how can I implement this in a more general way so that I can conveniently use this method for arbitrary classes, for example

val fields: List[String] = fieldNames[AnyCaseClass]

Is there a library that is already doing this for me?

+4
source share
1 answer

Something like this, maybe a slightly modified version of this example :

import shapeless._
import shapeless.ops.record._
import shapeless.ops.hlist.ToTraversable

trait FieldNames[T] {
  def apply(): List[String]
}

implicit def toNames[T, Repr <: HList, KeysRepr <: HList](
  implicit gen: LabelledGeneric.Aux[T, Repr],
  keys: Keys.Aux[Repr, KeysRepr],
  traversable: ToTraversable.Aux[KeysRepr, List, Symbol]
): FieldNames[T] = new FieldNames[T] {
  def apply() = keys().toList.map(_.name)
}

def fieldNames[T](implicit h : FieldNames[T]) = h()
+1
source

Source: https://habr.com/ru/post/1686753/


All Articles