Question

I'm trying to write a DSL that allows syntax like:

foo ["a", "b"], bar: { true }

Which I figured should be as easy as defining a method that accepts an attribute map as the first argument, e.g.:

def foo(Map attr, List blar) { ... }

But it seems like this syntax causes problems, wondering if anyone can explain why, and if there's a solution to allowing paren-free syntax like the line at the top.

Sample groovysh execution:

groovy:000> def foo(Map attr, List blar) { println attr; println blar; }
===> true
groovy:000> foo ["a", "b"], bar: { true }
ERROR org.codehaus.groovy.control.MultipleCompilationErrorsException:
startup failed:
groovysh_parse: 1: expecting EOF, found ',' @ line 1, column 15.
   foo ["a", "b"], bar: { true }
                 ^

1 error

        at java_lang_Runnable$run.call (Unknown Source)
Était-ce utile?

La solution

It won't work. It understands this as a getAt method call on a foo object:

foo["a", "b"]

and then the comma makes no sense.

You could use a varargs:

def foo(Map map, Object... args) { "$map $args" }
a = foo "a", "b", bar: {true}
println a // prints [bar:script_from_command_line$_run_closure1@1f3f7e0] [a, b]

Or reverse the param order:

def foo(Map map, args) { "$map $args" }
a = foo bar: {true}, ["a", "b"]
println a
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top