Home > database >  Flagging calls to mutator methods on immutable collections in IntelliJ
Flagging calls to mutator methods on immutable collections in IntelliJ

Time:01-20

It is well known that Java immutable collections provide mutator methods owing their existence to the (unfortunate but well documented) fact that both mutable and immutable collections of a particular type implement the same superinterface. The immutable implementations' mutators will throw the UnsupportedOperationException at runtime, and that, typically, is where the story ends——and where my questions begins. The following code is clearly highlighted as problematic by IntelliJ: enter image description here

What does IntelliJ know that javac doesn't? (This is JDK 17, in case it matters.)

CodePudding user response:

Intellij knows that a List created by List.of(..) is always immutable. So it doesn't make sense to add another element to that list.

However the return type of List.of(..) is simply the List interface. So

var films = List.of("Citizen Kane")

is equal to

List<String> films = List.of("Citizen Kane")

for javac. As you pointed out the list interface has an add()-Method so compiling this code is perfectly fine.

Or in other words. Javac just checks syntax while IntelliJ also has rudimentary semantic checks.

Edit: to add he technical term, IntelliJ uses static analysis to give those warnings and suggestions. Read about it in their block right here

  • Related