user1432980 user1432980 - 2 months ago 11
Groovy Question

why groovy does not coerce to final classes

Recently I've run into that Groovy does not allow coercion to final classes.

final class Example {
def x
}

// GroovyCastException. cannot coerce because it is final class
def a = { x = 5 } as Example


Why is that? I guess it is something with the mechanism that Groovy use to coerce to classes?

Answer

Your code, but working would be:

@groovy.transform.ToString(includeNames=true)
final class Example {
    def x
}

def a =  [x:5] as Example

println a // Example(x:5)