Making an object immutable in Groovy

groovy, immutability

Solution

If you are sure that `MutableObject` is effectively immutable you can do

@Immutable( knownImmutableClasses=[ MutableObject ] )
class MyObject {
    MutableObject mutableObject
}

Obviously care must be taken if this is a lie and mutableObject mutates ;-)

Problem

In Groovy I can make objects immutable by doing: ``` @Immutable class MyObject { ... } ``` But, if MyObject has a reference to a mutable object as in ``` @Immutable class MyObject { MutableObject mutableObject } ``` I can't. I get: ``` classes only support properties with effectively immutable types including ``` But, even thou myObject has a MutableObject, the reference to it will never change. Is there anything I can do to make `MyObject` as immutable as possible?

Original source