why does this throw an exception?
messageSource.getMessage('UserService.msg.forgot.unknown', ["[email protected]"], null)
unless I do this...
def Object[] args = ["[email protected]"]
messageSource.getMessage('UserService.msg.forgot.unknown', args, null)
Because ["[email protected]"] evaluates to an ArrayList, not an array:
groovy:000> o = ["asdf"]
===> [asdf]
groovy:000> o.getClass()
===> class java.util.ArrayList
OTOH your declaration creates an array of Objects:
groovy:000> Object[] args = ["asdf"]
===> [Ljava.lang.Object;@14e113b
and the method you're calling needs an array. You can create an array using as
:
Object[] args = ["asdf"] as Object[]
The Groovy creators made a point of making higher-level data structures like lists idiomatic, while arrays are present for interoperability with Java.
In his interview in Coders at Work Guy Steele talks about choices made in designing a language:
"There's this Huffman encoding problem. If you make something concise, something is going to have to be more verbose as a consequence. So in designing a language, one of the things you think about is, 'What are the things I want to make very easy to say and very easy to get right?' But with the understanding that, having used up characters or symbols for that purpose, you're going to have to make something else a little bit harder to say."
It certainly looks like Groovy made lists more concise, with the side effect that arrays became more verbose.
Nathan has already (correctly) explained the reason for this behavior at the language level. I just want to move one abstraction level up: Why are you using Spring's MessageSource
directly, in the first place? In Grails there is a message
tag, that wraps the message source:
g.message(code: 'UserService.msg.forgot.unknown', args: ["[email protected]"])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With