让代码发音
def bars = foo.listBars() def firstBar = bars ? bars.first() : null def firstBarBetter = foo.listBars()?.getAt(0)
是否有更优雅或习惯的方式来获取列表的第一个元素,如果不可能,则为null? (我不会考虑这里的try-catch块优雅。)
解决方法
不确定使用find是最优雅还是惯用的,但它很简洁,不会抛出IndexOutOfBoundsException。
def foo foo = ['bar','baz'] assert "bar" == foo?.find { true } foo = [] assert null == foo?.find { true } foo = null assert null == foo?.find { true }