在Groovy中以惯用方式获取列表的第一个元素
发布时间:2020-12-14 16:37:02 所属栏目:大数据 来源:网络整理
导读:让代码发音 def bars = foo.listBars()def firstBar = bars ? bars.first() : nulldef firstBarBetter = foo.listBars()?.getAt(0) 是否有更优雅或习惯的方式来获取列表的第一个元素,如果不可能,则为null? (我不会考虑这里的try-catch块优雅。) 解决方法
让代码发音
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 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |