Get the first element of a list idiomatically in Groovy

后端 未结 3 1626
我寻月下人不归
我寻月下人不归 2020-12-30 21:00

Let the code speak first

def bars = foo.listBars()
def firstBar = bars ? bars.first() : null
def firstBarBetter = foo.listBars()?.getAt(0)

3条回答
  •  醉话见心
    2020-12-30 22:01

    Not sure using find is most elegant or idiomatic, but it is concise and wont throw an IndexOutOfBoundsException.

    def foo 
    
    foo = ['bar', 'baz']
    assert "bar" == foo?.find { true }
    
    foo = []
    assert null == foo?.find { true }
    
    foo = null
    assert null == foo?.find { true }  
    

    --Update Groovy 1.8.1
    you can simply use foo?.find() without the closure. It will return the first Groovy Truth element in the list or null if foo is null or the list is empty.

提交回复
热议问题