程式扎記: [ 常見問題 ] Named parameters for Closure/Method

標籤

2015年4月7日 星期二

[ 常見問題 ] Named parameters for Closure/Method

Source From Here 
Question 
I have method 
  1. def test(String a, String b) { }  
and I would like to call this with a dynamic parameter map. I always though that: 
  1. test(['1','2']); //valid call  
and also 
  1. test([a:'1',b:'2']); //=> does not work  
will work. but it doesn't. So I remembered the spread operator, but can't get it to work.... 

Is there a way to call a method like the one above with some kind of map as parameter instead of single parameters? 

How-To 
Maybe I missed something, but I don't think Groovy has named parameters right now. There are discussions and proposals, but I'm not aware of anything official. For your case, I think the map spread may help, but not in every case. Upon getting the values, it follows the order in which the map values were declared: 
  1. package howto  
  2.   
  3. def test(String a, String b) { "a=$a, b=$b" }  
  4. def test(Map m) { test m*.value }  
  5.   
  6. class Obj{  
  7.     public String test(String a="a", String b="b"){ return "a=$a, b=$b" }  
  8. }  
  9.   
  10. assert test(a: "aa", b:"bb") == "a=aa, b=bb"  
  11. assert test(b: "aa", a:"bb") == "a=aa, b=bb" // should be false :-(  
  12. assert test(b: "ccc", a:"ddd") == "a=ccc, b=ddd" // should have worked :-(  
  13.   
  14. Obj o = new Obj()  
  15. assert o.test("aa""bb") == "a=aa, b=bb"  
  16. assert o.test(*["ccc""ddd"]) == "a=ccc, b=ddd"  
  17.   
  18. def otest = o.&test  
  19. assert otest("aa""bb") == "a=aa, b=bb"  
  20. assert otest(*["ccc""ddd"]) == "a=ccc, b=ddd"  
  21.   
  22. printf("Done!\n")  
Supplement 
[ GroovyGN ] Turn Methods into Closures 
[ Groovy Doc ] Dynamic Groovy 
[ In Action ] Dynamic object orientation - Defining classes and scripts

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!