score:8
Basically, it can't be done.
The JVM offers nothing by way of a Method handle (remember, Scala properties are encoded as methods in bytecode to support the uniform access principle). The closest you can get is to use reflection to find a list of methods defined on a particular class - which I appreciate doesn't help with your particular need.
It is possible to implement this as a Scala feature, but it would require a compiler plugin to grab the relevant symbol name from the AST and push it into code as a string literal, so not something I could demonstrate in a short code snippet :)
The other naming problem that often comes up in reflection is method parameters. That one at least I can help with. I have a work-in-progress reflection library here that's based on the compiler-generated scala signature as used by scalap
. It's nowhere near being ready for serious use, but it is under active development.
score:1
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.
score:1
This can be achieved with Scala 3 Macros (does it at compile time).
Create a Macro object (this must be in a separate file):
import scala.quoted.{Expr, Quotes}
object NameFromVariable :
def inspectCode(x: Expr[Any])(using Quotes): Expr[String] =
val name = x.show.split("""\.""").last
Expr(name)
Then you need an inline
method in your class.
inline def getIntVarName(inline x: Any): Any = ${ NameFromVariable.inspectCode('x) }
And use this method, like:
val myInt = 3
assert("myInt" === getIntVarName(myInt))
See the official documentation: https://docs.scala-lang.org/scala3/guides/macros/macros.html
score:2
Scala doesn't yet have much more than Java in terms of metadata like this. Keep an eye on the Scala Reflection project, but I doubt that will offer access to local variables anytime soon. In the meantime, consider a bytecode inspector library like ASM. Another big caveat: local variable names are lost during compilation, so you'd need to compile in "debug" mode to preserve them.
score:10
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")
score:15
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
Source: stackoverflow.com
Related Query
- Get Scala variable name at runtime
- Get name of assigned variable at runtime in Scala
- Unable to get runtime type of a variable in Scala
- I want to get the type of a variable at runtime
- Scala pattern matching with lowercase variable name
- Scala - get function name
- Get the specific simple name of a generic type in Scala
- Is there a way to get proper report of runtime compilation errors in scala 2.10?
- How to cast a variable to certain runtime type got from TypeCast in Scala
- Can you get a class name as a constant for scala annotations?
- how to print variable name and value using a scala macro?
- Scala Macro get value for term name
- How to get the runtime value of parameter passed to a Scala macro?
- Get elements of type structure of row by name in SPARK SCALA
- How do I get the runtime Class of a parameterized Type in a Scala trait
- Scala - error: recursive variable name needs type
- Scala : get mixin interfaces at runtime
- How to get name of all methods in a scala trait
- scala get function name that was sent as param
- Scala: How can I get the name of a variable class in a function?
- Scala class inheritance with same variable name
- Scala Class Variable Name Hides Method Parameter Name
- How to use scala class member name as variable
- How do I get sbt to not try to compile a directory whose name ends in .scala as a Scala source file?
- Scala Ambiguous Variable Name Within A Method
- How to get the full class name of a dynamically created class in Scala
- Scala runtime reflections get all the members of a specific type even for inner classes
- How to get application.conf variable in an object using Scala and Play 2.5.x?
- Cast a variable to runtime type from existential typed TypeCast in Scala
- How to override trait variable name in Scala
More Query from same tag
- Is there a well-typed Scala (or Java) library to consume JSON Web APIs?
- JDBC calls wrapped in Scala Future
- Make compiler aware a Java function never returns
- Type mismatch using Jedis in Scala
- Slick match on encrypted variable
- How to specify the main class (in the root directory) for Mill to run?
- How to create a TypeTag manually?
- Seq empty test with specs2
- Cross Publishing of SBT Plugins not working
- Function1[T, U] => Function1[T, Option[U]]
- Play framework: how to enumerate java.io.Writer?
- NoSuchMethodError: org.apache.hadoop.conf.Configuration.getPassword
- How to implement an ADT for a container with one or many values in Scala
- Spark Sql Dataset get index number
- Scala: convert each digit in a string to an integer
- Removal of special characters in a txt file using spark
- Is it safe to use a WindowSpec with an undefined frame in Spark?
- How to set the default value for a varargs parameter in scala?
- Using sbt with custom Scala builds
- In Scala how to access match case value in each case block
- Use of ' -> ' and ' <- ' operators in scala
- Mill: How to add additional Resources to a module
- setting default values with Play! Json Combinators
- Constructor.newInstance replaces Scala object
- Ternary operator in an anonymous function
- Iterating over cogrouped RDD
- Type mismatch from partition in Scala (expected (Set[String]...), actual (Set[String]...) )
- How to resolve scala.MatchError when creating a Data Frame
- Type erasure leads to missing parameter type for expanded function
- How to fetch from one stream first and then pass to another stream