Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy object array creation question

Tags:

grails

groovy

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) 
like image 230
Aaron Saunders Avatar asked Dec 21 '09 17:12

Aaron Saunders


2 Answers

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.

like image 145
Nathan Hughes Avatar answered Nov 09 '22 19:11

Nathan Hughes


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]"])
like image 30
Daniel Rinser Avatar answered Nov 09 '22 20:11

Daniel Rinser