Before making swapping
fashionable, classy and exciting, or in other word “Groovier”.
Let see what we do with our traditional Java to swap 2 values. If we
use Java way, we need a method that perform 3 step process of swapping
the value including declaration of additional variable.
In Java, what we do
:
int a=1, b=2, temp;
temp=a;
a=b;
b=temp;
println “a=${a},
b=${b}”
//Output : a=2, b=1
In Groovy, using
closure make it more simpler :
def a=1, b=2;
def swap = {x,y →
a=y; b=x;}
swap(a,b)
println “a=${a},
b=${b}”
//Output : a=2, b=1
Naaaaah! But still it's not
classy or cool enough to be Groovier. Let go more Groovy like real real Groovy.
Being more
Groovier, Aha! getting more excited to see magic and power of a Groovy :
def a=1, b=2;
(a,b)=[b,a]
//Output : a=2, b=1
Whoa! Wat was that do I just swap 2 values (a,b)=[b,a] and done all in
single line. :D
So are you still on 80's, 90's coding style or planning to join 21st
Century... ;)
Hope it helps! ;)
No comments:
Post a Comment