Get Scala variable name at runtime

后端 未结 5 1275
甜味超标
甜味超标 2020-12-16 17:03

Is it possible to get the name of a scala variable at runtime?

E.g. is it possible to write a function getIntVarName(variable: Int): String behaving as

5条回答
  •  天命终不由人
    2020-12-16 17:47

    For what you need to do, It seems to me that runtime is not required, since you already have your myInt variable defined at compile time. If this is the case, you just need a bit of AST manipulation via a macro.

    Try

    package com.natalinobusa.macros
    
    import scala.language.experimental.macros
    import scala.reflect.macros.blackbox.Context
    
    object Macros {
    
      // write macros here
      def getName(x: Any): String = macro impl
    
      def impl(c: Context)(x: c.Tree): c.Tree = {
        import c.universe._
        val p = x match {
          case Select(_, TermName(s)) => s
          case _ => ""
        }
        q"$p"
      }
    }
    

    Be aware that macro's must be compiled as a separate subproject, and cannot be part of the same project where the macro substitution has to be applied. Check this template on how to define such a macro sub-project: https://github.com/echojc/scala-macro-template

    scala> import Macros._
    import Macros._
    
    scala> val myInt = 3
    myInt: Int = 3
    
    scala> "myInt" == getName(myInt)
    res6: Boolean = true
    

提交回复
热议问题