在我的代码中,我发现有可能出现方法返回 null 的情况。在这种情况下,我宁愿抛出异常而不是返回 null。 但我不想使用常规的 if 语句,因为我认为它看起来很糟糕。请看以下代码:
class Type{}
@Field Queue<Type> q1 = [] as Queue
@Field Queue<Type> q2 = [] as Queue
Type regularMethod(){
Type toReturn = q1.poll() ?: q2.poll()
if(toReturn == null)
throw new RuntimeException("was null value")
return toReturn
}
Type myMethod(){
return q1.poll() ?: q2.poll() ?: exception()
}
Type exception(){
throw new RuntimeException("was null value")
}
你认为在这里使用Elvis运算符怎么样? 对你来说更易读吗? 或者有人能提出更好的解决方案吗?
return $q1.poll() || $q2.poll() || die();
... 但我在很大程度上同意这里其他帖子的观点。在Groovy的上下文中感觉很尴尬。 - Robert Hanson