我想知道为什么这种语法对于传播列表和 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/