8

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) 

2 Answers 2

18

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.

Sign up to request clarification or add additional context in comments.

2 Comments

makes sense, but seems to make the method a hassle to use, I guess I expected it to be more "groovy"
You could change it to ["[email protected]"].toArray(). Not much better but at least it's inline.
1

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]"])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.