It's been a surprise for me learning that the first() method to access the first element of a List in groovy throws an exception on an empty list even with a null-safe dereferencing operator:
//when List is null
def pList = null
assert 'null/empty' == pList ? 'not null/empty' : 'null/empty'
assert null == pList?.size()
assert null == pList?.first()?.toString()
try{
println pList[0]?.toString()
}
catch(all){
assert true
assert all in NullPointerException
}
//when List is empty
pList = []
assert 'null/empty' == pList ? 'not null/empty' : 'null/empty'
assert 0 == pList?.size()
assert null == pList[0]?.toString()
try{
pList?.first()?.toString()
}
catch(all){
assert true
assert all in NoSuchElementException
}
//when list is not empty
pList = [1,2,3,4]
assert 'not null/empty' == pList ? 'not null/empty' : 'null/empty'
assert 4 == pList?.size()
assert '1' == pList[0]?.toString()
assert '1' == pList?.first()?.toString()