Groovy closures - not understandable call order - groovy

I try to build a small DSL, but I don't understand the following order of execution.
The DSL has a statement as summarize tests of 'me'
my Groovy script for interpretation is:
def tests = {
[of: { who ->
println "IN CLOSURE"
"HALLO" // dummy value for testing
}]
}
def summarize(Closure c) {
println "SUMMARIZE - CALL CLOSURE"
def f = c()
println "SUMMARIZE - CALL CLOSURE"
println "RESULT $f"
f
}
and my caller script has
def g = summarize tests of 'me'
println g
The output is
SUMMARIZE - CALL CLOSURE
SUMMARIZE - CALL CLOSURE
RESULT [of:com.github.groovyclient.TestRailClient$_closure1$_closure13#470f1802]
IN CLOSURE
HALLO
I actually want to have the result of the tests closure already in the summarize method, but it seems that there the inner closure has not been called yet - what magic is happening after that so that the script does have the correct result ?
Can someone explain me, why the order of execution ? And how can I retrieve HALLO already in the summarize method ?
Thanks for any help

In your example, test is a closure which returns a map.
If you call test() you'll get [of: {...}]
It's what you see in your console, when you print f.
For groovy
summarize tests of 'me'
is equivalent to
summarize(tests).of('me')
yours summarize(tests) execute tests(), which returns the map [of:{..}]. After that, you're executing map.of which return the close, and then you are calling this closure with the parameters me.
There are differents options to obtain what you want, but it depends on the full "dsl" you want to implement, not just this special usecase. The easiest way I think with only this sentence, is returning an intermediate object, which is triggered when you call `of':
def summarize(t) {
return [
of: { who ->
def f = t().of(who)
println f
}
]
}

Related

Get Parameter list of a closure dynamically in Groovy

I have a Closure defined in a groovy file that load with the shell.evaluate() method.
I need to call this closure in by calling program using the shell."$closurename".call(arguments) call.
However to formulate the closure parameters ( argument above) I'd need to now what are the arguments and arguments names that the closure $Closurename accepts. Is there a way of dynamically knowing this in Groovy? I checked in the metaClass.method property but this does not work in my example below.
Below is the example code.
def arguments;
shell.evaluate(new File("/tmp/myGroovyClosureFile.groovy"))
testBlock = "myClosureName"
//Code here to find the parameters for myClosureName and create
//the arguments variable
shell."$testBlock".call(arguments)
As Jeff mentioned, it seems like groovy when generating code for closures anonymizes somehow the parameter names. However, you can still use reflection to get as much information as you can:
def cl = { int a, String b ->
println(a)
println(b)
}
def callMethod = cl.class.methods.find {
it.name == "call"
}
println callMethod.parameterTypes
println callMethod.parameters.name
and outputs:
[int, class java.lang.String]
[arg0, arg1]
Is there a way of dynamically knowing this in Groovy?
You can't really do it dynamically at runtime.

In the below code function is returning value of variable a, how is it possible, please explain

In the below code function myprint is returning value of variable a, how is it possible, please explain
class Test {
def myprint(){
def a = "my"
}
}
def test1 = new Test()
log.info test1.myprint()
You're encountering a groovy method without return statement.
Indeed, as stated in Groovy Goodness, as an example, the return statement is not mandatory to end a Groovy method : the result of the last executed instruction is used asmethod return value.
As a consequence, writing
def myMethod() {
def a = "value"
}
println myMethod()
will output
value
Because Groovy interpreter will consider def a = "value" as last instruction to be method return value.
However, for clarity reasons, and contrary to groovy commitee, I will suggest you not to use that feature, as it make code a little less readable.
Bonus point : this feature really goes well with closures : when calling [1,2,3].collect { it*2} will return [2, 4, 6] which is really nice.

Need help understanding currying using groovy closures?

I am trying to understand how currying works in functional programming. I have gone through wiki and a couple of questions about the same on SO.
Need help understanding lambda (currying)
What is 'Currying'?
I understand that currying is all about splitting a function that takes n arguments into n or less functions with one argument each. I theoretically comprehend it but I am not able to connect the dots while coding for the same. Perhaps it is my lack of knowledge in functional programming languages or C# (as many answers in the above questions deal with).
Anyway, I understand groovy & java. So I tried to get an outline for the standard add(a,b) function in groovy but I couldn't finish it.
def closure = { arg ->
// ??
}
def add(anotherClosure , a){
return closure // ??
}
Can someone help me understand currying using groovy closures?
You can roll your own currying functionality by writing a closure that takes another closure and a curried parameter to set, and returns a closure that uses this value.
// Our closure that takes 2 parameters and returns a String
def greet = { greeting, person -> "$greeting $person" }
// This takes a closure and a default parameter
// And returns another closure that only requires the
// missing parameter
def currier = { fn, param ->
{ person -> fn( param, person ) }
}
// We can then call our currying closure
def hi = currier( greet, 'Hi' )
// And test it out
hi( 'Vamsi' )
But you're better sticking with the inbuilt Groovy curry method as shown by jalopaba. (there is also rcurry and ncurry which curry from the right, and at a given position respectively)
It should be said, that the Groovy curry method is a misnomer as it is more a case of partial application as you do not need to get down to a closure requiring only a single parameter, ie:
def addAndTimes = { a, b, c -> ( a + b ) * c }
println addAndTimes( 1, 2, 3 ) // 9
def partial = addAndTimes.curry( 1 )
println partial( 2, 3 ) // 9
You can set a fixed value for one or more arguments to a closure instance using the curry() method:
def add = { a, b -> a + b }
def addFive = add.curry(5)
addFive(3) // 5 + 3 = 8
Another example:
def greeter = { greeting, name -> println "${greeting}, ${name}!" }
def sayHello = greeter.curry("Hello")
sayHello("Vamsi") // Hello, Vamsi!
def sayHi = greeter.curry("Hi")
sayHi("Vamsi") // Hi, Vamsi!

EachWithIndex groovy statement

I am new to groovy and I've been facing some issues understanding the each{} and eachwithindex{} statements in groovy.
Are each and eachWithIndex actually methods? If so what are the arguments that they take?
In the groovy documentation there is this certain example:
def numbers = [ 5, 7, 9, 12 ]
numbers.eachWithIndex{ num, idx -> println "$idx: $num" } //prints each index and number
Well, I see that numbers is an array. What are num and idx in the above statement? What does the -> operator do?
I do know that $idx and $num prints the value, but how is it that idx and num are automatically being associated with the index and contents of the array? What is the logic behind this? Please help.
These are plain methods but they follow quite a specific pattern - they take a Closure as their last argument. A Closure is a piece of functionality that you can pass around and call when applicable.
For example, method eachWithIndex might look like this (roughly):
void eachWithIndex(Closure operation) {
for (int i = 0; this.hasNext(); i++) {
operation(this.next(), i); // Here closure passed as parameter is being called
}
}
This approach allows one to build generic algorithms (like iteration over items) and change the concrete processing logic at runtime by passing different closures.
Regarding the parameters part, as you see in the example above we call the closure (operation) with two parameters - the current element and current index. This means that the eachWithIndex method expects to receive not just any closure but one which would accept these two parameters. From a syntax prospective one defines the parameters during closure definition like this:
{ elem, index ->
// logic
}
So -> is used to separate arguments part of closure definition from its logic. When a closure takes only one argument, its parameter definition can be omitted and then the parameter will be accessible within the closure's scope with the name it (implicit name for the first argument). For example:
[1,2,3].each {
println it
}
It could be rewritten like this:
[1,2,3].each({ elem ->
println elem
})
As you see the Groovy language adds some syntax sugar to make such constructions look prettier.
each and eachWithIndex are, amongst many others, taking so called Closure as an argument. The closure is just a piece of Groovy code wrapped in {} braces. In the code with array:
def numbers = [ 5, 7, 9, 12 ]
numbers.eachWithIndex{ num, idx -> println "$idx: $num" }
there is only one argument (closure, or more precisely: function), please note that in Groovy () braces are sometime optional. num and idx are just an optional aliases for closure (function) arguments, when we need just one argument, this is equivalent (it is implicit name of the first closure argument, very convenient):
def numbers = [ 5, 7, 9, 12 ]
numbers.each {println "$it" }
References:
http://groovy.codehaus.org/Closures
http://en.wikipedia.org/wiki/First-class_function
Normally, if you are using a functional programing language such as Groovy, you would want to avoid using each and eachWithIndex since they encourage you to modify state within the closure or do things that have side effects.
If possible, you may want to do your operations using other groovy collection methods such as .collect or .inject or findResult etc.
However, to use these for your problem, i.e print the list elements with their index, you will need to use the withIndex method on the original collection which will transform the collection to a collection of pairs of [element, index]
For example,
println(['a', 'b', 'c'].withIndex())
EachWithIndex can be used as follows:
package json
import groovy.json.*
import com.eviware.soapui.support.XmlHolder
def project = testRunner.testCase.testSuite.project
def testCase = testRunner.testCase;
def strArray = new String[200]
//Response for a step you want the json from
def response = context.expand('${Offers#Response#$[\'Data\']}').toString()
def json = new JsonSlurper().parseText(response)
//Value you want to compare with in your array
def offername = project.getPropertyValue("Offername")
log.info(offername)
Boolean flagpresent = false
Boolean flagnotpresent = false
strArray = json.Name
def id = 0;
//To find the offername in the array of offers displayed
strArray.eachWithIndex
{
name, index ->
if("${name}" != offername)
{
flagnotpresent= false;
}
else
{
id = "${index}";
flagpresent = true;
log.info("${index}.${name}")
log.info(id)
}
}

Groovy: what's the purpose of "def" in "def x = 0"?

In the following piece of code (taken from the Groovy Semantics Manual page), why prefix the assignment with the keyword def?
def x = 0
def y = 5
while ( y-- > 0 ) {
println "" + x + " " + y
x++
}
assert x == 5
The def keyword can be removed, and this snippet would produce the same results. So what's the effect of the keyword def ?
It's syntactic sugar for basic scripts. Omitting the "def" keyword puts the variable in the bindings for the current script and groovy treats it (mostly) like a globally scoped variable:
x = 1
assert x == 1
assert this.binding.getVariable("x") == 1
Using the def keyword instead does not put the variable in the scripts bindings:
def y = 2
assert y == 2
try {
this.binding.getVariable("y")
} catch (groovy.lang.MissingPropertyException e) {
println "error caught"
}
Prints: "error caught"
Using the def keyword in larger programs is important as it helps define the scope in which the variable can be found and can help preserve encapsulation.
If you define a method in your script, it won't have access to the variables that are created with "def" in the body of the main script as they aren't in scope:
x = 1
def y = 2
public bar() {
assert x == 1
try {
assert y == 2
} catch (groovy.lang.MissingPropertyException e) {
println "error caught"
}
}
bar()
prints "error caught"
The "y" variable isn't in scope inside the function. "x" is in scope as groovy will check the bindings of the current script for the variable. As I said earlier, this is simply syntactic sugar to make quick and dirty scripts quicker to type out (often one liners).
Good practice in larger scripts is to always use the "def" keyword so you don't run into strange scoping issues or interfere with variables you don't intend to.
Ted's answer is excellent for scripts; Ben's answer is standard for classes.
As Ben says, think of it as "Object" -- but it is much cooler in that it does not constrain you to the Object methods. This has neat implications with respect to imports.
e.g. In this snippet I have to import FileChannel
// Groovy imports java.io.* and java.util.* automatically
// but not java.nio.*
import java.nio.channels.*
class Foo {
public void bar() {
FileChannel channel = new FileInputStream('Test.groovy').getChannel()
println channel.toString()
}
}
new Foo().bar()
e.g. But here I can just 'wing it' as long as everything is on the classpath
// Groovy imports java.io.* and java.util.* automatically
// but not java.nio.*
class Foo {
public void bar() {
def channel = new FileInputStream('Test.groovy').getChannel()
println channel.toString()
}
}
new Foo().bar()
According to this page, def is a replacement for a type name and can simply be thought of as an alias for Object (i.e. signifying that you don't care about the type).
As far as this single script is concerned there is no practical difference.
However, variables defined using the keyword "def" are treated as local variables, that is, local to this one script. Variables without the "def" in front of them are stored in a so called binding upon first use. You can think of the binding as a general storage area for variables and closures that need to be available "between" scripts.
So, if you have two scripts and execute them with the same GroovyShell, the second script will be able to get all variables that were set in the first script without a "def".
The reason for "def" is to tell groovy that you intend to create a variable here. It's important because you don't ever want to create a variable by accident.
It's somewhat acceptable in scripts (Groovy scripts and groovysh allow you to do so), but in production code it's one of the biggest evils you can come across which is why you must define a variable with def in all actual groovy code (anything inside a class).
Here's an example of why it's bad. This will run (Without failing the assert) if you copy the following code and paste it into groovysh:
bill = 7
bi1l = bill + 3
assert bill == 7
This kind of problem can take a lot of time to find and fix--Even if it only bit you once in your life it would still cost more time than explicitly declaring the variables thousands of times throughout your career. It also becomes clear to the eye just where it's being declared, you don't have to guess.
In unimportant scripts/console input (like the groovy console) it's somewhat acceptable because the script's scope is limited. I think the only reason groovy allows you to do this in scripts is to support DSLs the way Ruby does (A bad trade-off if you ask me, but some people love the DSLs)
Actually, I don't think it would behave the same...
variables in Groovy still require declaration, just not TYPED declaration, as the right-hand side generally contains enough information for Groovy to type the variable.
When I try to use a variable that I haven't declared with def or a type, I get an error "No such property", since it assumes that I'm using a member of the class containing the code.

Resources