Wednesday, May 29, 2013

Immutable (Annotation)

import groovy.transform.Immutable

@Immutable
class A {
    Date d // private final
    Date z // private final
    
    /* //no constructor def'n needed with @Immutable
    public A(Date D, Date Z) {
        d = D
        z = Z
    }*/
}

A a = new A(new Date(), new Date())

println a // see provided toString()

Date d1 = a.d // get property
assert (d1 == a.d)
d1.setHours(0) // mutate copy of property
assert (d1 != a.d) // this would not pass if class was mutable

println a.d
a.d.setHours(0) // no consequence/ignored
println a.d

No comments:

Post a Comment