Question
I have method
- def test(String a, String b) { }
- test(['1','2']); //valid call
- test([a:'1',b:'2']); //=> does not 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:
- package howto
- def test(String a, String b) { "a=$a, b=$b" }
- def test(Map m) { test m*.value }
- class Obj{
- public String test(String a="a", String b="b"){ return "a=$a, b=$b" }
- }
- assert test(a: "aa", b:"bb") == "a=aa, b=bb"
- assert test(b: "aa", a:"bb") == "a=aa, b=bb" // should be false :-(
- assert test(b: "ccc", a:"ddd") == "a=ccc, b=ddd" // should have worked :-(
- Obj o = new Obj()
- assert o.test("aa", "bb") == "a=aa, b=bb"
- assert o.test(*["ccc", "ddd"]) == "a=ccc, b=ddd"
- def otest = o.&test
- assert otest("aa", "bb") == "a=aa, b=bb"
- assert otest(*["ccc", "ddd"]) == "a=ccc, b=ddd"
- printf("Done!\n")
* [ GroovyGN ] Turn Methods into Closures
* [ Groovy Doc ] Dynamic Groovy
* [ In Action ] Dynamic object orientation - Defining classes and scripts
沒有留言:
張貼留言