kduy
6/10/2015 - 9:05 AM

Simple macro to get the value of Val by name

Simple macro to get the value of Val by name

import scala.language.experimental.macros
import scala.reflect.macros.blackbox.Context

object Macros {
  def getValue(varName: String) = macro getValueImpl
  
  def getValueImpl(c: Context)(varName: c.Expr[String]): c.Expr[Any] = {
    import c.universe._
    val name = varName.tree match {
      case  Literal(Constant(x: String)) => x
      case _ => c.abort(c.enclosingPosition, "the parameter must be a String ")
    }
    c.Expr[Any](q"${TermName(name)}")
  }
}


// Note: must compile Macros object BEFORE Test object respectively
// Use  ':paste' if in RPL
// scala 2.11
object Test extends App {
  import Macros._
  val x = 100
  println(getValue("x"))
}