Groovy is not strict type script like java.
Groovy is case-sensitive
Variable
def principal=2000;
def principal=2000;
println "principal : $principal or ${principal} or "+principal
def amount = 1000 + principal
println "amount : $amount"
Variable can be referred in String as $principal or ${principal}
Variable will be referred by its name as well
Function
def doubleIt(n) {
n + n // Note we don't need a return statement
}
foo = 5
println "doubleIt($foo) = "+doubleIt(foo)
foo = "foobar"
println "doubleIt($foo) = ${doubleIt(foo)}"
Function can be referred in String as ${doubleIt(foo)}
Function can be referred outside of string as doubleIt(foo)
Closure
Is is different way of declaring the functions . They also capture variables from there enclosing environment.. Closure can be passed around to a different variable.
https://groovy-lang.org/closures.html
def foo ="One million dollars"
def myClosure = {
println "Hello from a closure"
println "The value of foo is $foo"
}
myClosure()
or
def bar = myClosure
def baz = bar
baz()
In closure the arguments are present on the left side of the arrow with comma separated .
We can pass closure as parameter to a function.
def double_It = {x -> x+x }
def sum_It = {x,y -> x+y}
def number1 =5
def number2 =10
def result= double_It 5
println "result is $result"
result = sum_It 5,10
println "result is $result"
def applyTwice(func,arg){
func(func(arg))
}
def doubledtwice = applyTwice(double_It,number1)
println "Applying doubelit twice to $number1 equals $doubledtwice"
https://www.infoworld.com/article/2073966/groovy-scripts-master-their-own-classpath-with-rootloader.html
No comments:
Post a Comment