Array initalization behaviour

Hello, I just encountered this behaviour depending on how Arrays are initialized - is this a bug or do I get something mixed up? Thanks !

(
a = [List(), List()];
a[0].add(1);
a;
// = [ List[ 1 ], List[ ] ] - as expected
)

(
b = Array.fill(2, List());
b[0].add(1);
b;
// =  [ List[ 1 ], List[ 1 ] ] - not as expected
)

This should be:

b = Array.fill(2, { List() });

hjh

1 Like

You’re also encountering a common gotcha here. The contract with the add method is that it returns a collection with the value added - it may mutate the underlying collection or return a new collection. Always you need to do a = a.add(1) unless you KNOW you are working with a collection that always mutates itself - List mutates so capturing the return value isn’t strictly necessary, but Array has a fixed size so often adding a new value requires that a new array be allocated and returned.

I think @maciej intentionally uses List to avoid the ugly and annoying a[0] = a[0].add(...) idiom. But it’s always worth pointing out because it is indeed a common gotcha!

Thanks all - that´s exactly why I use List at places where the size is not defined at initalization. But that {} got me this time.

1 Like