Groovy Syntax Confusion - groovy

I'm new to Groovy/Gradle and I'm currently learning the syntax, but I'm a bit confused by its syntax because it seems that same thing can be achieved by a lot of different ways. Does anyone know what's the meaning of the following groovy code:
something(x, y) {
// some code here
}
It is definitely not a method declaration because it doesn't have the def keyword. It also doesn't look like an invocation of the something method, because that wouldn't explain the curly braces. What exactly does this code do?

It is definitely not a method declaration because it doesn't have the
def keyword.
Method definitions do not require the def keyword.
It also doesn't look like an invocation of the something method,
because that wouldn't explain the curly braces. What exactly does this
code do?
something(x, y) {
// some code here
}
It is an invocation of a method. That code is invoking a method named something and passing 3 parameters. x and y are the first 2 parameters and a groovy.lang.Closure is the 3rd. That code is the same as the following:
def closure = {
// some code here
}
something(x, y, closure)

Related

syntax on nodejs function

I'm starting right now with coding on JS. There are a few things that I don't understand pretty well, and I'm a little bit confused because I have tried almost all, and I don't get to solve the error. Would someone provide me some help or guidance with this.
my code
function ImparPar(NumIp) {
if(NumIp % 2 === 0) {
return 'Par';
} else {
return 'Impar';
}
}
Your function definition (on Line 1) has the following:
The function keyword
A function name (ImparPar)
A formal parameter (NumIP)
All these make this a function definition.
When you are calling the function later on in the code (line 13) you just need to call it by name. e.g.:
ImparPar(2);
When you are calling a function, you pass it - what is called - an actual parameter (in your case 2).
When you prefix it with the function keyword, it is interpreted as a function definition and therefore does not expect an actual parameter, and instead expects a formal parameter.
If you remove the function keyword from line 13 it should work as expected for you, and just execute the function.

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.

How to make closure have its own copy of variable -does groovy have lambda

What is the command in groovy to ensure a class variable is unaffected by a closure? As we know a closure captures the environment that its wrapped in. So, if I have a closure that increments an integer class variable for example, then that variable is changed for the class. What I want is for a closure to have its own copy of a variable so it does not affect the class variable. Is it possible? In Objective C for example we would use the __Block command and that would make the block be able to change the value of a captured variable. Now, I am asking for the opposite of __Block in my case as closures are already changing the variables they are scoped in.
Lets take a look at a clear example of what I want:
def class myCoolClass {
def x=1
def myMethodThatReturnsClosure(){
//lets return a closure who's scope will include the x=1
myClosure
}
def showMeXFromMyCoolClass(){
println "this is x from myCoolClass:$x"
}
def myClosure={
println "im printing x:$x"
//lets change x now from within closure
x++
}
}
def x = new myCoolClass();
def c=x.myMethodThatReturnsClosure();
c(); //we are changing x ...x = 1
c(); //we are changing x again ...x = 2
c(); //we are changing x again ...x = 3
x.showMeXFromMyCoolClass(); //...x = 4
//i dont want x to be 4 in the last call, i want x to be 1.
//i want it unchanged. how to tell closure to take its own copy
I realize in groovy a closure knows about its environment. It "closes out" around the function that its wrapped in. Is there lambda in groovy then? I think lambda would not know about its environment right? But lets say I want only want variable to not know about its environment and others should, then lambda would not be good.
Your example code is not valid Groovy syntax. You may want to debug it and update the example with the fixes. Nevertheless, you got your point across.
One way of making the closure use a copy of the class variable is to make a copy of the variable and use it instead of x in the closure.:
def myMethodThatReturnsClosure() {
def myX = x
{
println "im printing x:$myX"
myX++
}
}
This assumes the variable is a primitive, which grooy handles differently so that a copy is made. Otherwise the new variable would just be a reference to the original. In the latter case, you'd have to clone the object to get a copy.

What is the use of "use" keyword/method in groovy?

I read use keyword in Groovy. But could not come out with, for what it has been exactly been used. And i also come with category classes, under this topic,what is that too? And from, Groovy In Action
class StringCalculationCategory {
static def plus(String self, String operand) {
try {
return self.toInteger() + operand.toInteger()
} catch (NumberFormatException fallback) {
return (self << operand).toString()
}
}
}
use (StringCalculationCategory) {
assert 1 == '1' + '0'
assert 2 == '1' + '1'
assert 'x1' == 'x' + '1'
}
With the above code, can anyone say what is the use of use keyword in groovy? And also what the above code does?
See the Pimp My Library Pattern for what use does.
In your case it overloads the String.add(something) operator. If both Strings can be used as integers (toInteger() doesn't throw an exception), it returns the sum of those two numbers, otherwise it returns the concatenation of the Strings.
use is useful if you have a class you don't have the source code for (eg in a library) and you want to add new methods to that class.
By the way, this post in Dustin Marx's blog Inspired by Actual Events states:
The use "keyword" is actually NOT a keyword, but is a method on
Groovy's GDK extension of the Object class and is provided via
Object.use(Category, Closure). There are numerous other methods
provided on the Groovy GDK Object that provide convenient access to
functionality and might appear like language keywords or functions
because they don't need an object's name to proceed them. I tend not
to use variables in my Groovy scripts with these names (such as is,
println, and sleep) to avoid potential readability issues.
There are other similar "keywords" that are actually methods of the Object class, such as with. The Groovy JDK documentation has a list of such methods.
A very good illustration is groovy.time.TimeCategory. When used together with use() it allows for a very clean and readable date/time declarations.
Example:
use (TimeCategory) {
final now = new Date()
final threeMonthsAgo = now - 3.months
final nextWeek = now + 1.week
}

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