Groovy 转换行为不一致

标签 groovy

我今天遇到了一段糟糕的代码,相当于:

[["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/

相关文章:

java - JAXB @XmlSchema 位置被忽略

Java 对象在调试器中具有属性,但没有 getter 方法

grails - 如何从另一个 Grails 插件配置 Grails 插件

groovy - 如何访问特征中的私有(private)方法

grails - 在grails中,为什么我必须为条件创建一个变量?

data-binding - Grails 数据绑定(bind)

groovy - GGTS 无法运行 Groovy Shell

java - 在grails中读取文件

gradle - Gradle:在自定义独立插件中使用 'maven-publish'插件

regex - Groovy 扩展正则表达式语法