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 "${[*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

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 :

4

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like