Created
April 6, 2016 13:40
-
-
Save swsnr/4b7becbea955ae909af7426d2e2e166c to your computer and use it in GitHub Desktop.
Get a list of all case class attributes with shapeless
This file contains 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 shapeless._ | |
import shapeless.poly._ | |
import shapeless.record._ | |
import shapeless.ops.record._ | |
import shapeless.ops.hlist.{Mapper,ToTraversable} | |
import shapeless.tag._ | |
final case class Message(id: Int, title: String, body: String) | |
trait ToAttributes[T] { | |
def toAttributes(v: T): Seq[String] | |
} | |
object Attributes { | |
object symbolName extends Poly1 { | |
implicit def atTaggedSymbol[T] = at[Symbol with Tagged[T]](_.name) | |
} | |
implicit def familyFormat[T, Repr <: HList, KeysRepr <: HList, MapperRepr <: HList]( | |
implicit gen: LabelledGeneric.Aux[T, Repr], | |
keys: Keys.Aux[Repr, KeysRepr], | |
mapper: Mapper.Aux[symbolName.type, KeysRepr, MapperRepr], | |
traversable: ToTraversable.Aux[MapperRepr, List, String] | |
): ToAttributes[T] = | |
new ToAttributes[T] { | |
def toAttributes(v: T): Seq[String] = keys().map(symbolName).toList.toSeq | |
} | |
def toAttributes[T](v: T)(implicit c: ToAttributes[T]): Seq[String] = c.toAttributes(v) | |
} | |
import Attributes._ | |
val message = Message(10, "foo", "bar") | |
val attributes = toAttributes(message) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment