Skip to content

Instantly share code, notes, and snippets.

@rabitarochan
Created February 20, 2015 02:06
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 rabitarochan/d36c6bb20d3b7a523c78 to your computer and use it in GitHub Desktop.
Save rabitarochan/d36c6bb20d3b7a523c78 to your computer and use it in GitHub Desktop.
nameOf macro
import scala.language.experimental.macros
import scala.reflect.macros.whitebox.Context
object NameOf {
def nameOf[A](expr: A => Any): String = macro nameOf_macro[A]
def nameOf_macro[A: c.WeakTypeTag](c: Context)(expr: c.Expr[A => Any]): c.Expr[String] = {
import c.universe._
expr.tree match {
case Function(_, tree) =>
c.Expr[String](Literal(Constant(
tree.symbol.name.encodedName.toString()
)))
case _ => throw new Exception
}
}
}
case class Person(name: String, age: Int)
object NameOfSample {
import NameOf._
def main(args: Array[String]): Unit = {
println(nameOf[Person](_.name))
// "name"
println(nameOf[Person](_.age))
// "age"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment