如何从groovy中的返回函数接受多个参数 [英] how to accept multiple parameters from returning function in groovy

查看:32
本文介绍了如何从groovy中的返回函数接受多个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从用 groovy 编写的函数返回多个值并接收它们,但出现错误

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

org.codehaus.groovy.ast.expr.ListExpression 类,其值为 '[a,b]', 是一个糟糕的表达式,作为赋值的左侧操作员

class org.codehaus.groovy.ast.expr.ListExpression, with its value '[a, b]', is a bad expression as the left hand side of an assignment operator

我的代码是

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 [a*10,a*20]
}

推荐答案

您几乎拥有它.从概念上讲 [ a, b ] 创建一个列表,而 ( a, b ) 解开一个列表,所以你想要 (a,b)=f1(a) 而不是 [a,b]=f1(a).

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' ]
}

这篇关于如何从groovy中的返回函数接受多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆