Groovy强制转换表现不一致

Luk*_*e E 3 groovy

我今天碰到了一大堆代码,等同于:

[["asdf"]].each {String str -> println str}

println (["asdf"] as String)
Run Code Online (Sandbox Code Playgroud)

把它放到groovy console(groovysh)中,你就会看到这个:

asdf

[asdf]
Run Code Online (Sandbox Code Playgroud)

谁能解释为什么输出有差异?

tim*_*tes 5

如果这意味着它将适合您在闭包中定义的类型,Groovy将解包List.

如果您没有定义类型(或将其设置为List),它将按预期运行:

// Both print '[a]'
[['a']].each { it -> println it }
[['a']].each { List it -> println it }
Run Code Online (Sandbox Code Playgroud)

但是,如果您定义了类型,它将尝试解包列表并将内容应用于定义的参数,因此:

// Prints 'a'
[['a']].each { String it -> println it }
Run Code Online (Sandbox Code Playgroud)

把它想象成java中的varargs,或者用closure( *it )Groovy 调用闭包

它实际上非常有用,因为你可以做以下事情:

// 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"
}
Run Code Online (Sandbox Code Playgroud)