如何在groovy中接受来自返回函数的多个参数 [英] how to accept multiple parameters from returning function in groovy
问题描述
我想从一个用groovy编写的函数中返回多个值并接收它们,但是我得到一个错误
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.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
我的代码是
My code is
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' ]
}
另外,您可以合并声明和赋值: / p>
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屋!