DEV Community

Discussion on: Java 15 in 2020: Reasons to *not* use Java?

 
tim_klug profile image
Tim Klug

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.

public class Main {

    public static void main(String[] args) {
        var a = "a";
        var b = "b";
        var c = "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:


void doSomething(List<Item> items, Data someDate) {
  ...
}

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.

Thread Thread
 
brunoborges profile image
Bruno Borges • Edited
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:

        var a = "a";
        var b = "b";
        var c = "c";

        var list = List.of(a, b, c);
        list.forEach(it -> it = null); // mutate the data
        System.out.println(list);  // prints [a, b, c]

        for(var x : list) {
          x = null;
        }
        System.out.println(list); // prints [a, b, c]

The data continues to be immutable.

Thread Thread
 
michelemauro profile image
michelemauro

If you need val immutability, Scala is just a few jars away, And VSCode support with Metals is getting really good.