blue-sky
blue-sky

Reputation: 53806

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

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);

Upvotes: 4

Views: 707

Answers (2)

Paolo Falabella
Paolo Falabella

Reputation: 25844

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.

Upvotes: 3

Brian Agnew
Brian Agnew

Reputation: 272257

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

Upvotes: 9

Related Questions