Aseem Bansal
Aseem Bansal

Reputation: 6972

null.collect() returns empty list

I was writing unit tests when I happened to find that in groovy the below is true

null.collect({ //Anything }) == []

I could not find the reason for this. What part of groovy is giving this behavior? I checked NullObject but that does not have this collect method. So how is this happening?

Upvotes: 3

Views: 1514

Answers (2)

halex
halex

Reputation: 16403

In groovy null has the iterator() method which returns an empty iterator. Calling collect on null is the same as null.iterator().collect({/*whatever*/}) and so this will be [].

See the comment on this bug report.

Upvotes: 2

Opal
Opal

Reputation: 84844

collect method is added to all objects at runtime via DefaultGroovyMethods class, see here, so every class has this methods:

class Lol {}

assert new Lol().collect({}) == [null]
assert new Lol().iterator().toList() //is not empty, contains 'this'

Upvotes: 1

Related Questions