Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DSL with Groovy -> passing parameter values

Tags:

groovy

dsl

I'm new to Groovy and I'm trying to write a mini DSL for some specific task. For this purpose I've been trying to solve a problem like this below: I'd like to print (and/or return) 5 by calling this code (without using parantheses):

give me 5 

I expected that a definition like this below would work:

def give = {clos ->  return clos} 
def me = {clos ->  println clos; return clos} 

but actually it doesn't. Could you please help me how to define "give" and "me" in order to return the value 5 with the expression "give me 5" where me must be a closure, give could be also metaClass, property etc.

Thanks in advance! Iv

like image 947
ivita Avatar asked Oct 23 '22 13:10

ivita


1 Answers

Groovy 1.8+ takes

give me 5

and the parser effectively tries to do:

give( me ).5

So, if you write your code like this, it works:

def give = { map ->  map } 
def me = [:].withDefault { it }

a = give me 5

println a

prints:

5
like image 67
tim_yates Avatar answered Oct 30 '22 20:10

tim_yates