Created
February 20, 2015 02:06
-
-
Save rabitarochan/d36c6bb20d3b7a523c78 to your computer and use it in GitHub Desktop.
nameOf macro
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 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 | |
} | |
} | |
} |
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
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