程式扎記: [ Groovy 常見問題 ] how to accept multiple parameters from returning function in groovy

標籤

2015年1月26日 星期一

[ Groovy 常見問題 ] how to accept multiple parameters from returning function in groovy

Source From Here 
Question 
I want to return multiple values from a function written in groovy and receive them , but i am getting an error: 
 

The code: 
  1. int a=10  
  2. int b=0  
  3. println "a is ${a} , b is ${b}"  
  4. [a,b]=f1(a)  
  5. println "a is NOW ${a} , b is NOW ${b}"  
  6.   
  7. def f1(int x) {     
  8.   return [a*10,a*20]  
  9. }  
How-To 
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)
  1. int a=10  
  2. int b=0  
  3. println "a is ${a} , b is ${b}"  
  4. (a,b)=f1(a)  
  5. println "a is NOW ${a} , b is NOW ${b}"  
  6.   
  7. def f1(int x) {  
  8.     return [x*10,x*20]  
  9. }  
By the way, if you want to retrieve key/value of Map as tuple, you can refer to below code: 
  1. import java.util.Map.Entry  
  2.   
  3. def m = ['a':1'b':2]  
  4.   
  5. def e = m.entrySet()  
  6.   
  7. class MapItems implements Iterable{  
  8.     Set mapSet;  
  9.       
  10.     public MapItems(Set mset)  
  11.     {  
  12.         this.mapSet = mset  
  13.     }  
  14.       
  15.     class _Iter implements Iterator{  
  16.         Iterator iter  
  17.           
  18.         public _Iter(Iterator i){iter=i}  
  19.   
  20.         @Override  
  21.         public boolean hasNext() {  
  22.             iter.hasNext();  
  23.         }  
  24.   
  25.         @Override  
  26.         public List next() {  
  27.             Entry e = iter.next()  
  28.             return [e.key, e.value]  
  29.         }  
  30.   
  31.         @Override  
  32.         public void remove() {  
  33.             throw new java.lang.UnsupportedOperationException()           
  34.         }         
  35.     }  
  36.   
  37.     @Override  
  38.     public Iterator iterator() {  
  39.         new _Iter(mapSet.iterator())  
  40.     }  
  41. }  
  42.   
  43. Map.metaClass.items = {return new MapItems(delegate.entrySet())}  
  44.   
  45. Iterator itemIter = m.items().iterator()  
  46. while(itemIter.hasNext())  
  47. {  
  48.     // Retrieve key/value as tuple  
  49.     (k,v) = itemIter.next()  
  50.     printf("$k=$v\n")  
  51. }  
Supplement 
[ Groovy Doc ] ExpandoMetaClass - Domain-Specific Language

沒有留言:

張貼留言

網誌存檔