Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean to set a mutable object to 'val'?

Tags:

scala

I'm setting a java Pojo instance variable to 'val' & changing its state after it's initialized. Will this cause any issues since its really a 'var' ?

val st = new Pojo();
st.setInt(0);
like image 870
blue-sky Avatar asked Dec 16 '22 16:12

blue-sky


2 Answers

It's still a val. The reference can't be changed, but the object referred to can have its internal state mutated.

val means you can't do this reassignment:

val st = new Pojo()
st = new Pojo()      // invalid!

For this you need a var:

var st = new Pojo()
st = new Pojo()      // ok
like image 137
Brian Agnew Avatar answered Jan 06 '23 06:01

Brian Agnew


it's not a var. Try doing st=new Pojo() again and you will see that you can't reassign a new value to st (the compiler will complain error: reassignment to val).

val does not grant a "deep" immutability, just that the value initially set (which is just a reference to an object that can be mutable) can't be changed to a new reference.

like image 20
Paolo Falabella Avatar answered Jan 06 '23 06:01

Paolo Falabella