带冒号的 Groovy 扩展运算符映射语法

标签 groovy

我想知道为什么这种语法对于传播列表和 map 不一致。例如在这段代码中

def list =[1,2,3]
def map =[a:1,b:2]
println "${[*list]}"
println "${[*:map]}"

列表以单个 * 展开,并以 * 进行映射:

它与传播运算符内部的工作方式有关吗?因为没有看到 *map 构造的任何其他用法(比如用 [:] 定义一个空映射,以便将它与列表区分开来)。

最佳答案

展开运算符 (*) 用于从集合中提取条目并将它们作为单独的条目提供。

1. Spread list elements:

When used inside a list literal, the spread operator acts as if the spread element contents were inlined into the list:

def items = [4,5]               
def list = [1,2,3,*items,6]             
assert list == [1,2,3,4,5,6] 


来源:http://docs.groovy-lang.org/latest/html/documentation/#_spread_list_elements

2. Spread map elements:

The spread map operator works in a similar manner as the spread list operator, but for maps. It allows you to inline the contents of a map into another map literal, like in the following example:

def m1 = [c:3, d:4]         
def map = [a:1, b:2, *:m1] 
assert map == [a:1, b:2, c:3, d:4]​


来源:http://docs.groovy-lang.org/latest/html/documentation/#_spread_map_elements

关于带冒号的 Groovy 扩展运算符映射语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39849618/

相关文章:

java - Jenkins 管道和 java.nio.file.* 方法的问题

groovy - 如何获取 Geb 模块实例及其声明的类?

groovy - 如何在Groovy中获得今天的日期

regex - 组合多个正则表达式模式

java - 用于在 Java 中 pretty-print 时间段的库,仅提供最重要的字段

grails - Groovy:将 PermSize 从 IntellijIdea 传递给 groovy 编译器

groovy - 使用 groovy 在 IntelliJ IDE 中运行 Cucumber Geb 测试时出错

groovy - 带有 SoapUI groovy 的 Shell 命令

groovy - Groovy ASTTransformation-在闭包内部执行forLoop的collectionExpression

java - 如何使用 EasyMock 模拟 Java.net.URL 类