In Scala Shell, I can declare same variable multiple times and I am not getting any error/warning
For Example
scala> val a = 1
a : Int = 1
scala> val a = 2
a : Int = 2
scala> val a = 1
a : Int = 1
scala> lazy val a = 1
a : Int = <lazy>
Here variable name "a" is declared multiple times with var
, val
and lazy val
So I would like to know
val a = 1
and var a = 2
which is higher precedence?var
and val
?Note: In IntelliJ, Able to declare same variable with multiple time and I don't see error but while accessing IDE shows error as "Can not resolve varibale" so what is the use the declaring same variable multiple times?
In the repl, there is often experimenting and prototyping taking place, and redefining a val is most often not by mistake, but intentional.
Precedence is taken what you typed finally successful.
scala> val a: Int = 7
a: Int = 7
scala> val a: Int = "foo"
<console>:12: error: type mismatch;
found : String("foo")
required: Int
val a: Int = "foo"
^
scala> a
res7: Int = 7
If you aren't sure, whether a name is already in use, you may just type the name, like a
in my case, and get a feedback. For undeclared values, you get:
scala> b
<console>:13: error: not found: value b
b
^
But if you paste a block of code with the :pas
technique, multiple names in conflict won't work and the whole block is discarded.