Get Scala variable name at runtime

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

    You can use scala-nameof to get a variable name, function name, class member name, or type name. It happens at compile-time so there's no reflection involved and no runtime dependency needed.

    val myInt = 3
    assert("myInt" === nameOf(myInt))
    

    will compile to:

    val myInt = 3
    assert("myInt" === "myInt")
    

提交回复
热议问题