作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想从用 groovy 编写的函数返回多个值并接收它们,但出现错误
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)
。
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]
}
另一个返回对象的示例,它们不需要是相同的类型:
final Date foo
final String bar
(foo, bar) = baz()
println foo
println bar
def baz() {
return [ new Date(0), 'Test' ]
}
此外,您可以结合声明和赋值:
final def (Date foo, String bar) = baz()
println foo
println bar
def baz() {
return [ new Date(0), 'Test' ]
}
关于groovy - 如何从groovy中的返回函数接受多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6757539/
我是一名优秀的程序员,十分优秀!