I ran into a bad chunk of code today that equates to this:
[["asdf"]].each {String str -> println str}
println (["asdf"] as String)
Put this into groovy console (groovysh) and you’ll see this come out:
asdf
[asdf]
Can anyone explain why there’s a difference in the outputs?
Groovy will unwrap a List if it means it will fit into the types you have defined in your closure.
If you don’t define the type (or set it as List), it will behave as you expect:
If however you define a type, it will attempt to unwrap the list and apply the contents to the defined parameters, so:
Think of it like varargs in java, or calling the closure with
closure( *it )in GroovyIt actually comes in pretty useful as you can do things like: