when I run the following codes, the "error: reassignment to val" be thrown, anyone knows why?
def main(args: Array[String]) :Unit = {
var a = 10
def Fun(a:Int):Unit = {
while( a < 20 ){
println( "Value of a: " + a );
a = a + 1 // Error: reassignment to val
}
}
Fun(a)
}
If I want to implement the function of variable a plus one in the function Fun, how to modify it?
You're hiding the
a
outer variable with the method parametera
which is aval
"automatically".You wrote the same as:
I guess you want to remove the method parameter as you want to increment the outer variable which is accessible as you're defining an inner method:
Keep in mind this is not idiomatic Scala code and it's not clear what you're trying to achieve so I cannot provide a better solution for you it you definitely don't want to write such code in real projects.