Created
July 19, 2018 10:37
-
-
Save danslapman/fc527935a27ac99b8f568b8c3247f62e to your computer and use it in GitHub Desktop.
Get field names of case class using shapeless
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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