How to Reassignment to a Val in Scala
This article will teach about reassignment to a val
in Scala.
Reassignment to a val
in Scala
In Scala, reassignment to val
is not allowed, but we can create a new val
and assign the value to it.
Example code 1:
object MyClass {
def main(args: Array[String])
{
val x = 10;
x = x+10
println(x)
}
}
Output:
error: reassignment to val
We can see an error when reassigning the values to a val
.
As a workaround, we can assign the result to a new val
and use it.
Example code 2:
object MyClass {
def main(args: Array[String])
{
val x = 10;
val y = x+10
println(y)
}
}
Output:
20
Scala provides us with three ways to define things.
-
val
is used to define a fixed value, which cannot be modified.Example code: Here, the val
x
cannot be modified.object MyClass { def main(args: Array[String]) { val x = 10; } }
-
var
is used to define a variable, a value that can be modified.object MyClass { def main(args: Array[String]) { var x = 10; x = x+10; println(x) x = x*1000 println(x) } }
Output:
20 20000
-
def
is used to define a methodExample code:
object MyClass { def student = 2*3*4*5*6 def main(args: Array[String]) { println(student) } }
Output:
720
Conclusion
In this article, we learned that we could not reassign values to a val
as it declares the variable as the fixed value, so if we want to use a variable that keeps changing constantly, we can use var
.