Get Scala variable name at runtime

后端 未结 5 1270
甜味超标
甜味超标 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:54

    I don't think it's possible to get the name of a variable, but you can try it with objects:

    object Test1 {
      def main(args: Array[String]) {
        object MyVar {
          def value = 1
        }
        println(MyVar.getClass)
      }
    }
    

    This prints: class Test1$MyVar$2$. So you can get 'MyVar' out of it.

提交回复
热议问题