Groovy Spread Operator Map Syntax with Colon
I'm Wondering Why This Syntax Is Not Consistent for Spreading Lists and Maps. for Example in This Code Def List =[1,2,3] Def Map =[A:1, B:2] Println...
I'm wondering why this syntax is not consistent for spreading lists and maps. For example in this code
def list =[1,2,3]
def map =[a:1,b:2]
println "${[*list]}"
println "${[*:map]}"
list is spreaded with single *, and map with *:
Is it connected to how spread operator internally works? Because didn't see any other usage for *map construct (like defining an empty map with [:] makes sense to distinguish it from list).
1 Answer
The spread operator (*) is used to extract entries from a collection and provide them as individual entries.
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]
Source :
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]
Source :