Skip to content

Instantly share code, notes, and snippets.

@rahilb
Created January 4, 2017 12:14
Show Gist options
  • Save rahilb/7a0c3309d587c069e8663ce11f4b918f to your computer and use it in GitHub Desktop.
Save rahilb/7a0c3309d587c069e8663ce11f4b918f to your computer and use it in GitHub Desktop.
Macro
import FieldList._
import shapeless.{HList, LabelledGeneric}
import scala.language.experimental.macros
import scala.reflect.macros.blackbox
object Foo {
def foo_impl[T, L <: HList](c: blackbox.Context)
(t: c.Expr[T])
(gen: c.Expr[LabelledGeneric.Aux[T, L]],
fl: c.Expr[FieldList[L]]): c.Expr[String] = {
import c.universe._
reify {
val sb = new StringBuilder
val obj = t.splice
val generic = gen.splice
val fieldList = fl.splice
// T.fieldList returns a List[String] of the class' fields.
obj.fieldList(generic, fieldList).foldLeft(sb) { case (builder, next) =>
builder.append(next)
builder.append(" -> ")
builder.append() // How to get the value of obj.$next?
}.toString()
}
}
def foo[T, L <: HList](t: T)(implicit gen: LabelledGeneric.Aux[T, L], fl: FieldList[L]): String = macro foo_impl[T, L]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment