From my point of view I mostly use the of() functions to create a data structure. But while the list itself is immutable the elements are still mutable.
publicclassMain{publicstaticvoidmain(String[]args){vara="a";varb="b";varc="c";List.of(a,b,c).forEach(it->it=null);// mutate the data}}
And I think here is the think that often ends in the NPE hell. Some people write very protective code, where everything that could be null, is checked for null. There is no concept like val from the Kotlin world.
So from what I saw in the code bases I worked with is, that some people are using something like this:
When I go through those methods, they mutate some items or all of the list. Now here you need to be aware, that the list is passed by ref. So testing and complexity of the code is not super trivial anymore. So what I meant with first class citizen is the idea, that from my point of view it should be easy to not mutate a state and write pure functions and mutating the state should need much more verbosity code. But that is what I think.
List.of(a,b,c).forEach(it->it=null);// mutate the data
This code doesn't change the data at all. The list continues to be the same after the forEach. This code above is the same as this:
vara="a";varb="b";varc="c";varlist=List.of(a,b,c);list.forEach(it->it=null);// mutate the dataSystem.out.println(list);// prints [a, b, c]for(varx:list){x=null;}System.out.println(list);// prints [a, b, c]
Passionate developer in Java and Scala. And sometimes, something else. A few months per year, someone calls me "professor". CoFounder of Scala By The Lagoon @scalagoon
From my point of view I mostly use the
of()
functions to create a data structure. But while the list itself is immutable the elements are still mutable.And I think here is the think that often ends in the NPE hell. Some people write very protective code, where everything that could be
null
, is checked fornull
. There is no concept likeval
from the Kotlin world.So from what I saw in the code bases I worked with is, that some people are using something like this:
When I go through those methods, they mutate some items or all of the list. Now here you need to be aware, that the list is passed by ref. So testing and complexity of the code is not super trivial anymore. So what I meant with first class citizen is the idea, that from my point of view it should be easy to not mutate a state and write pure functions and mutating the state should need much more verbosity code. But that is what I think.
This code doesn't change the data at all. The list continues to be the same after the forEach. This code above is the same as this:
The data continues to be immutable.
If you need
val
immutability, Scala is just a few jars away, And VSCode support with Metals is getting really good.