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).
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 : 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]
Source : http://docs.groovy-lang.org/latest/html/documentation/#_spread_map_elements
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With