Java 9’s Immutable Collections Are Easier To Create But Use With Caution
Code is easier to reason about when collections cannot be altered after their creation. Having to keep track of the current state of a collection as it gets passed around from this method to that equates to more mental balls to juggle. Mutating the state of methods` arguments is called a side effect and is a cardinal sin of functional programming. Since immutability is almost inarguably better why do Java developers generally completely ignore it?
Instantiating an Immutable Collection in Java 8
Creating immutable collections in Java is convoluted to the point that it’s probably not worth the price of admission. This is a best practice implementation of an immutable set in Java 8:
Set<String> set = Collections.unmodifiableSet(new HashSet<>(Arrays.asList("darth", "plagueis", "the", "wise")));
By comparison, here’s the same thing in Scala:
val set = Set("darth", "plagueis", "the",
Continue reading →