Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy spread operator map syntax with colon

Tags:

groovy

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).

like image 799
Vuk Djapic Avatar asked Mar 12 '23 00:03

Vuk Djapic


1 Answers

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

like image 72
Prakash Thete Avatar answered Apr 30 '23 13:04

Prakash Thete