Search code examples
scalavariablesdefinition

How to check if a variable is val or var programmatically?


In scala, we can define variable like: val a=10 or var a=10.

Is there anyway we can check if a is a val or var programmatically?


Solution

  • Scala is an object-oriented language. This means, in particular, that you can only manipulate objects.

    Variables are not objects in Scala (like pretty much every programming language), therefore there is no way that you could, for example, call a method on a variable to ask it whether it is a var or a val (because you can only call methods on objects, and variables aren't objects), and there is no way to pass a variable to a method to ask the method whether the variable is a val or a var (because you can only pass objects as arguments, and variables aren't objects).

    Again, this is not really specific to Scala, this applies to the overwhelming majority of programming languages. Even in programming languages like Ruby with very powerful dynamic meta programming capabilities, variables aren't objects and cannot be reflected upon.

    But wait, you might say, classes aren't objects in Scala either, but I can get a runtime representation of a class using scala.Predef.classof[T]! Indeed you can, but there is a fundamental difference between classes and variables: classes are runtime entities, so even if they don't exist as objects, they do at least exist at runtime. Variables are a pure compile time construct, they do not exist at runtime.

    So, the only way you can get at a variable at all is using compile-time reflection. Which, very likely, is complete overkill for whatever it is that you want to do.

    So, to answer your question:

    Is there anyway we can check if a is a val or var programmatically?

    Extremely short answer: No.

    Very short answer: You shouldn't use var anyway. If you follow that advice, the question becomes moot.

    Short answer: If your local variable scopes are so big and convoluted that you cannot even figure out whether a variable is a var or a val you have much bigger problems.

    Simple answer: No.

    Slightly more elaborate answer: No, not at runtime.

    Very complex answer: It is probably possible using Compile-Time Reflection.