how to accept multiple parameters from returning function in groovy

后端 未结 3 1207
终归单人心
终归单人心 2020-12-24 10:40

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

class org.codehaus.groovy.ast.expr.Lis

相关标签:
3条回答
  • 2020-12-24 11:04

    You can declare and assign the variables in which the return values are stored in one line like this, which is a slightly more compact syntax than that used in Justin's answer:

    def (int a, int b) = f1(22)
    

    In your particular case you may not be able to use this because one of the variables passed to f1 is also used to store a return value

    0 讨论(0)
  • 2020-12-24 11:13

    You almost have it. Conceptually [ 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]
    }
    

    Another example returning objects, which don't need to be the same type:

    final Date foo
    final String bar
    (foo, bar) = baz()
    println foo
    println bar
    
    def baz() {
        return [ new Date(0), 'Test' ]
    }
    

    Additionally you can combine the declaration and assignment:

    final def (Date foo, String bar) = baz()
    println foo
    println bar
    
    def baz() {
        return [ new Date(0), 'Test' ]
    }
    
    0 讨论(0)
  • 2020-12-24 11:14

    When running Groovy in the context of Jenkins pipeline job the above answers do not work (at least on version 2.60.2), but the following does:

    node {
        obj = ret2()
        fw = obj[0]
        lw = obj[1]
        echo "fw=${fw}"
        echo "lw=${lw}"
    }
    
    def ret2()
    {
        return [5, 7]
    }
    

    Or alternatively:

    node {
        obj = ret2()
        fw = obj.a
        lw = obj.b
        echo "fw=${fw}"
        echo "lw=${lw}"
    }
    
    def ret2()
    {
        return [a:5, b:7]
    }
    
    0 讨论(0)
提交回复
热议问题