Skip to content

Instantly share code, notes, and snippets.

@danslapman
Created July 19, 2018 10:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save danslapman/fc527935a27ac99b8f568b8c3247f62e to your computer and use it in GitHub Desktop.
Save danslapman/fc527935a27ac99b8f568b8c3247f62e to your computer and use it in GitHub Desktop.
Get field names of case class using shapeless
import $ivy.`com.chuusai::shapeless:2.3.3`
import shapeless._
trait Fields[T] {
def fields: List[String]
override def toString: String = fields.mkString(", ")
}
object Fields extends LabelledProductTypeClassCompanion[Fields] {
def apply[T](fs: List[String]): Fields[T] = new Fields[T] {
override def fields: List[String] = fs
}
implicit val string: Fields[String] = apply[String](Nil)
implicit def anyVal[T <: AnyVal]: Fields[T] = apply[T](Nil)
object typeClass extends LabelledProductTypeClass[Fields] {
override def product[H, T <: HList](name: String, ch: Fields[H], ct: Fields[T]) : Fields[H :: T] =
Fields(name :: ct.fields)
override def emptyProduct : Fields[HNil] = Fields(Nil)
override def project[F, G](instance: => Fields[G], to: F => G, from: G => F) = Fields(instance.fields)
}
}
case class Foo(bar: String, baz: Boolean)
println(implicitly[Fields[Foo]].fields)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment