DSL with Groovy & # 8594; transmitting parameter values

I am new to Groovy and I am trying to write a mini DSL for some specific task. To do this, I am trying to solve a problem similar to the one below: I would like to print (and / or return) 5 by calling this code (without using brackets):

give me 5 

I was expecting a definition like this below to work:

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

But actually it is not. Could you help me how to define "give" and "I" to return the value 5 with the expression "give me 5", where I should be a closure, also give a metaclass, property, etc.

Thanks in advance! Iv

+5
source share
3 answers

Groovy 1.8+ accepts

give me 5

and the parser effectively tries to:

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

:

5
+3

. .

give(me(5)) or 
give me(5)

, , , , .

five = me 5
give five
+1

? :

give me 5

, :

give("me", 5)
give "me", 5 //equivalent "DSL" notation
give("you", 7)
give "you", 7 //equivalent "DSL" notation

//or...
def me= "Mickey", you= "Donald"
give(me, 5)
give me, 5 //equivalent "DSL" notation
give(you, 7)
give you, 7 //equivalent "DSL" notation

If it never changes me, semantics are closest to:

giveMe(5)
giveMe 5 //equivalent "DSL" notation

You wrote: “I have to be closing” and “I want my rules to work without parentheses,” starting with syntax restrictions. Always start with semantic requirements :-)

-1
source

All Articles