Question
I want to return multiple values from a function written in groovy and receive them , but i am getting an error:
The code:
- int a=10
- int b=0
- println "a is ${a} , b is ${b}"
- [a,b]=f1(a)
- println "a is NOW ${a} , b is NOW ${b}"
- def f1(int x) {
- return [a*10,a*20]
- }
You almost have it. [ a, b ] creates a list, and ( a, b ) unwraps one, so you want (a,b)=f1(a) instead of [a,b]=f1(a).
- int a=10
- int b=0
- println "a is ${a} , b is ${b}"
- (a,b)=f1(a)
- println "a is NOW ${a} , b is NOW ${b}"
- def f1(int x) {
- return [x*10,x*20]
- }
- import java.util.Map.Entry
- def m = ['a':1, 'b':2]
- def e = m.entrySet()
- class MapItems implements Iterable
- {
- Set
mapSet; - public MapItems(Set
mset) - {
- this.mapSet = mset
- }
- class _Iter implements Iterator
- {
- Iterator
iter - public _Iter(Iterator
i){iter=i} - @Override
- public boolean hasNext() {
- iter.hasNext();
- }
- @Override
- public List next() {
- Entry e = iter.next()
- return [e.key, e.value]
- }
- @Override
- public void remove() {
- throw new java.lang.UnsupportedOperationException()
- }
- }
- @Override
- public Iterator
- iterator() {
- new _Iter(mapSet.iterator())
- }
- }
- Map.metaClass.items = {return new MapItems(delegate.entrySet())}
- Iterator itemIter = m.items().iterator()
- while(itemIter.hasNext())
- {
- // Retrieve key/value as tuple
- (k,v) = itemIter.next()
- printf("$k=$v\n")
- }
* [ Groovy Doc ] ExpandoMetaClass - Domain-Specific Language
沒有留言:
張貼留言