在Groovy中以惯用方式获取列表的第一个元素

让代码发音

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 }

相关文章

背景:    8月29日,凌晨4点左右,某服务告警,其中一个...
https://support.smartbear.comeadyapi/docs/soapui/steps/g...
有几个选项可用于执行自定义JMeter脚本并扩展基线JMeter功能...
Scala和Java为静态语言,Groovy为动态语言Scala:函数式编程,...
出处:https://www.jianshu.com/p/ce6f8a1f66f4一、一些内部...
在运行groovy的junit方法时,报了这个错误:java.lang.Excep...