Ada*_*deg 30 groovy list idiomatic
让代码先发言
def bars = foo.listBars()
def firstBar = bars ? bars.first() : null
def firstBarBetter = foo.listBars()?.getAt(0)
Run Code Online (Sandbox Code Playgroud)
是否有更优雅或惯用的方式来获取列表的第一个元素,如果不可能则为null?(我不会在这里考虑优雅的试试块.)
Joh*_*ner 58
不确定使用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 }
Run Code Online (Sandbox Code Playgroud)
Jam*_*hon 17
你也可以这样做
foo[0]
Run Code Online (Sandbox Code Playgroud)
这将抛出一个NullPointerException当foo是空的,但它会空列表,不像返回空值foo.first(),这将扔在空异常.