Search code examples
groovynamed-parameters

Named parameters


I have method

def test(String a, String b) { }

and I would like to call this with a dynamic parameter map. I always though that

test(['1','2']); //valid call

and also

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?


Solution

  • 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:

    def test(String a, String b) { "a=$a, b=$b" }
    def test(Map m) { test m*.value }
    
    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=ddd, b=ccc" // should have worked :-(
    

    For classes, may I suggest Groovy's as operator?

    @groovy.transform.CompileStatic
    class Spread {
      class Person {
        String name
        BigDecimal height
      }
    
      def method(Person p) {
        "Name: ${p.name}, height: ${p.height}"
      }
    
      def method(Map m) { method m as Person }
    
      static main(String[] args) {
        assert new Spread().method(name: "John", height: 1.80) == 
          "Name: John, height: 1.80"
      }
    }