User Guide: List and Map literals


(davidmichaelkarr) #1

Section 13.5.4, “List and map literals”, tries to show examples of using both list and map literals. It seems to show examples of list literals, but the map literal example isn’t really a “literal” as I would expect.

For the "Map Literal’ section, it just shows this:

// Map literal
apply plugin: 'java'
Map<String, String> map = new HashMap<String, String>()
map.put('plugin', 'java')
apply(map)

I tried several variations of that “map” declaration and initialization, but I couldn’t find any reasonable alternatives. For instance, I tried this:

Map<String, String> map = [name:"Gromit", likes:"cheese", id:1234]

But that fails with “No such property: name for class: org.gradle.api.internal.plugins.DefaultObjectConfigurationAction”. I’m not sure what is reasonable to do here.

This is obviously more of a Groovy question, but we need to address this in the user guide.


(Luke Daley) #2
apply plugin: 'java'

That’s the map literal syntax.

Map<String, String> map = new HashMap<String, String>()

map.put(‘plugin’, ‘java’)

apply(map)

That’s the same thing not using map literal syntax.


(davidmichaelkarr) #3

OH.

But it appears that the syntax used by “apply” is different from the “conventional” map literal. I can do this:

Map map = [plugin:'java']

but I can’t do:

apply [plugin:'java']

or:

Map map = plugin:'java'

So the “apply” call does not and can not have the wrapping brackets, but a typical place where a map value can be supplied (value assignment, for instance) requires the wrapping brackets.


(Luke Daley) #4
apply [plugin:'java']

Would need to be:

apply([plugin:'java'])

What’s confusing things here is that Groovy’s named argument syntax is incorrectly being referred to as Map literal syntax.

http://mrhaki.blogspot.com.au/2009/09/groovy-goodness-named-parameters-are.html

While the two are very closely related, not making the distinction leads to the kind of confusion you are facing.


(davidmichaelkarr) #5

Cute. So this example isn’t even demonstrating map literals, just something that “looks like” a map literal, which is then internally converted to a map as it’s passed to the method.

This distinction seems like a useful thing to point out. I’ll see if I can expand this example a bit more to clarify this.