Can someone please explain me how this code works?

Can someone explain me the logic behind this code? My values are 3 and 1 but I don’t understand how the answers are 2 and 1
object revision2 {
def main(args: Array[String]): Unit = {
print("Enter first integer: ");
var value1:Int=readInt();
print(“Enter second integer: “);
var value2:Int=readInt();
value1 match{
case 1=>value2+=1;
case 2=>value2-=4;
case 3 =>value1=value2 *2;
case 4 =>value1-=3;
case 5=>value2+=1;
case _=>value1=value2+1;
}
println(“value1=”+value1+”,value2=”+value2);
}
}

enter code here

Since value1 and value2 are mutable, value1 matches on 3 and then updates itself to become 2.

Value2 is unchanged, so the final outputs are 2 and 1.

1 Like

can you please explain me what is a mutable value?

Scala supports val vs. var
the val identifier marks values that are immutable. The compiler will throw an error if you try to reassign them.
the var identifier marks variables that are mutable. You can reassign them.

Functional programming, which Scala is geared to support, promotes copying of values as opposed to mutating them. If you can work out much of your code to avoid mutating variables you will have code that can be easily made to run on parallel processors and also avoids a large class of errors that are a result of mutating variables incorrectly.

Because of the above main reasons, you will see the val identifier and the heavy promotion of its use when discussing Scala. Using val will force you to do many things differently in the subsequent code.

1 Like

Thank you so much for your explanation sir!

If I may ask, is it the editor that is causing the lack of proper indenting of code?

Thanks,
Andre