Last Updated: February 25, 2016
·
14.11K
· lizard5472

Difference between << and + operators in Groovy maps

Hey there... I've got a problem with these guys...

There is no defference in the result of these two operations.
You can use plus operator:
assert [ a: 1, b: 1 ] + [ a: 0 ] == [ a: 0, b: 1 ]
Or left shift:
assert [ a: 1, b: 1 ] << [ a: 0 ] == [ a: 0, b: 1 ]
And the result would be all the same.

But...

The difference is that << adds the right map into the left map, and when you use +, Groovy constructs a new Map based on the left map, and adds the right map into it.

So when you need to change a left Map instance - use << operator,
but when you need to create a new Map instance based on two or more maps - use + operator.