Search code examples
groovy

In Groovy, Is there any way to safely index into a Collection similar to the safe navigation operator?


This will safely return null without throwing any exceptions

obj?.prop1?.prop2

How can I do that for collections, where it won't throw an index out of bounds exception?

myarray[400]  //how do I make it return null if myarray.size() < 400 

Is there such an operator for Collections?


Solution

  • That's the default behavior with all collections except arrays in groovy.

    assert [1,2,3,4][5] == null
    def test = new ArrayList()
    assert test[100] == null
    assert [1:"one", 2:"two"][3] == null
    

    If you've got an array, cast it to a list.

    def realArray = new Object[4]
    realArray[100] // throws exception
    (realArray as List)[100] // null
    

    You can string list and map indexes together with the ? operator in the same way as with properties:

    def myList = [[name: 'foo'], [name: 'bar']]
    assert myList[0]?.name == 'foo'
    assert myList[1]?.name == 'bar'
    assert myList[2]?.name == null