Constant field declarations should use the immutable type (such as ImmutableList) instead of the general collection interface type (such as List)


The problem

A field initialized to hold an immutable collection should be declared using the Immutable* type itself (such as ImmutableList), not the general collection interface type (such as List), or Iterable. This communicates several very useful semantic guarantees to consumers, as explained in the documentation.

Although these classes are technically not interfaces (in order to prevent unauthorized implementations), they are actually interfaces in the sense used by Effective Java 3rd Edition §64 (“Refer to objects by their interfaces”).

So, prefer this:

static final ImmutableList<String> COUNTRIES =
    ImmutableList.of("Denmark", "Norway", "Sweden");

over this:

static final List<String> COUNTRIES =
    ImmutableList.of("Denmark", "Norway", "Sweden");

or this:

static final Iterable<String> COUNTRIES =
    ImmutableList.of("Denmark", "Norway", "Sweden");

TIP: Using the immutable type for the field declaration allows Error Prone to prevent accidental attempts to modify the collection at compile-time (see ImmutableModification).


Suppress false positives by adding the suppression annotation @SuppressWarnings("MutableConstantField") to the enclosing element.