小编Ord*_*don的帖子

使用 elvis 运算符抛出异常 Groovy

在我的代码中,我发现我的方法可能返回 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")
}
Run Code Online (Sandbox Code Playgroud)

您认为在这里使用 elvis 运算符怎么样?它对你来说更具可读性吗?或者有人可以建议更好的解决方案吗?

groovy

5
推荐指数
1
解决办法
6472
查看次数

标签 统计

groovy ×1