maditya
maditya

Reputation: 8896

Does Java allow immutability checks at compile-time?

I know of at least 2 mechanisms to enforce that a Collection should not be modified:

However, I notice both of them enforce the contract at runtime, by throwing exceptions (e.g UnsupportedOperationException).

Questions:

  1. Are there existing libraries/language features that allow immutability checks to be performed at compile-time?
  2. If not, why not? Is it because of a language limitation, the result of a design decision, or some other reason?

Upvotes: 4

Views: 486

Answers (2)

Brian Kent
Brian Kent

Reputation: 3854

The original authors of the Collections APIs (unfortunately) did not make a distinction between immutable and mutable collections. An immutable API would have no mutating methods (but would likely rebuild collections internally as Persistent data structure).

See Scala as an example of a Collections API on the JVM that supports both immutable and mutable collections.

Upvotes: 2

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272647

You could only do this by having no mutating methods on the class. But you're stuck if you want to implement an existing interface that has methods with mutating semantics (even static analysis won't help you in the general case).

Upvotes: 2

Related Questions