Skip to content

Instantly share code, notes, and snippets.

@nightscape
Forked from danslapman/fields.sc
Created April 3, 2020 15:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nightscape/2a01cb338a8c53460fe0afadb7c58614 to your computer and use it in GitHub Desktop.
Save nightscape/2a01cb338a8c53460fe0afadb7c58614 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)
implicit def hkt[F[_], T]: Fields[F[T]] = apply[F[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