1

I came across this in code a few times, and cannot figure out what this declaration is exactly. It appears to simply be a collection of variables, but is being passed together as though it is some singular variable or object itself holding all 3 values. What exactly is this?

def foo(filename) {
    // Below you can find an assignment I don't understand:
    def (id, company, type) = roo(filename)
    AClass.findByStuff(id, company, type)
}
Szymon Stepniak
  • 40,216
  • 10
  • 104
  • 131
William Tolliver
  • 305
  • 1
  • 2
  • 16

1 Answers1

1

This is Groovy's multiple assignment feature. In short words - it expects a collection of elements on the right side and a list of variables in brackets to assign elements from the list to on the left side. For instance:

def (a, b, c) = [1, 10, 100, 1000]

assert a == 1
assert b == 10
assert c == 100

This assignment prevents from throwing IndexOutOfBoundsException and if the number of variables on the left side is greater than the number of elements in collection on the right side, then it simply assigns null value, for instance:

def (a, b, c) = [1, 10]

assert a == 1
assert b == 10
assert c == null
Szymon Stepniak
  • 40,216
  • 10
  • 104
  • 131
  • Thanks! Question though. Why did the assignment skip the value 10(second index) when assigning? Also once this declaration is made, it can namelessly be passed around as though it is a variable correct? similar to the way it was in my OP code? – William Tolliver Nov 01 '18 at 18:32
  • 1
    That was a typo. It assigns values in order. And yes - after assignment these variables can be used as a regular variables. This is just a shorthand version of assigning multiple variables based on values taken from a collection. – Szymon Stepniak Nov 01 '18 at 18:36