Hi,

I am trying to understand some behaviour that is causing subtle and odd
bugs in our code.

The behaviour is essentially that under very specific circumstances, Groovy
is coercing a List of Maps to a single Map. A condensed example is:

   class Foo {
        def foo(Map obj) {
            println(obj)
        }
    }
    z = [
        [ a: 1, b:2]
    ]
    f = new Foo()
    f.foo(z)

In here, even though the foo() method requires a Map, the call does not
throw a type mismatch exception. Instead, the foo() method receives the Map
object that is the first entry of the list as its argument. Consequently,
it prints:

[a:1, b:2]

If instead, it is passed a list containing two Maps, eg: z = [ [ a: 1,
b:2], [c:1, d:2] ], then it does throw a type conversion error. Also
notable is that it will always throw the type conversion error if you
attempt to coerce it outside the context of a function call, for example,
using z.asType(Map).

So it seems that under very specific circumstances that is both code
context and data dependent, Groovy will perform a different type of type
conversion to what it would do otherwise.

Can anyone explain why it does this and what the rationale is?

Cheers,

Simon

Reply via email to