当前在Groovy中,我需要编写以下内容以实现简单逻辑:
def sampleList = [1, 2]
def element = sampleList.find { it == 3 }
if (!element) {
throw new IllegalStateException('Element not found!')
}
使用Java流,这只是更简单:
def sampleList = [1, 2]
sampleList.stream().filter { it == 3 }.findFirst().orElseThrow {
new IllegalStateException('Element not found!')
}
是否还有其他简洁的Groovy语法可以执行相同的任务?
选项1 我认为这是最清晰的,利用Optional
API:
def sampleList = [1, 2]
def element = Optional.ofNullable(sampleList.find{it==3}).orElseThrow{new IllegalStateException('Element not found!')}
选项2
我不认为这很棒,但是您可以从封闭中调用throw
,并使用猫王?:
操作员
def sampleList = [1, 2]
def element = sampleList.find{it==3} ?: {throw new IllegalStateException('Element not found!')}()
//Alternately: ...{throw new IllegalStateException('Element not found!')}.call() to make it more readable
投掷:
Exception thrown
java.lang.IllegalStateException: Element not found!
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at ConsoleScript20$_run_closure2.doCall(ConsoleScript20:2)
at ConsoleScript20$_run_closure2.doCall(ConsoleScript20)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at ConsoleScript20.run(ConsoleScript20:2)
at jdk.internal.reflect.GeneratedMethodAccessor218.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
在Groovy Console中
选项3 另一个选项是将所有逻辑提取到指定的关闭中:
def sampleList = [1, 2]
def tester = {list, value -> if(value in list){value} else{throw new IllegalStateException('Element not found!')}}
tester(sampleList, 3)