我今天遇到了一段糟糕的代码,相当于:
[["asdf"]].each {String str -> println str}
println (["asdf"] as String)
将它放入 groovy 控制台 (groovysh
),你会看到这样的结果:
asdf
[asdf]
谁能解释为什么输出有差异?
最佳答案
Groovy 将展开一个列表,如果这意味着它适合您在闭包中定义的类型。
如果您不定义类型(或将其设置为 List),它将按您预期的方式运行:
// Both print '[a]'
[['a']].each { it -> println it }
[['a']].each { List it -> println it }
但是,如果您定义了一个类型,它将尝试解包列表并将内容应用于定义的参数,因此:
// Prints 'a'
[['a']].each { String it -> println it }
把它想象成 java 中的可变参数,或者在 Groovy 中用 closure( *it )
调用闭包
它实际上非常有用,因为您可以执行以下操作:
// Tokenize the strings into 2 element lists, then call each with these
// elements in separate variables
['a=b', 'b=c']*.tokenize( '=' )
.each { key, value ->
println "$key = $value"
}
关于Groovy 转换行为不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12416631/