Search code examples
javajava-8functional-interface

Inmutable instances/functional interfaces in Java


Is there any way to force an instance or a functional interface static method output to be inmutable in a fashion like Collections.immutable(x)?

I'd like for instance to create sort of Comparator functional interface and disallow chained operations like ".thenComparing()" for some of the static builder-like methods created instances.


Solution

  • You can force your return value to be immutable by returning an instance of an immutable class. There is no general purpose way to make instances of your class immutable without knowing what the class does.

    The second paragraph of your question contains an incorrect assumption that .thenComparing(...) makes a comparator mutable. thenComparing leaves the original comparator intact and makes a new comparator.