在 JavaScript
中我们可以重写:
if (ua.isEmpty()) {
return false;
}
else if (ua.contains('curl')) {
return false;
}
进入这个以获得清晰的代码:
switch(true) {
case ua.isEmpty():
return false;
case ua.contains('curl'):
return false;
}
有什么建议我们可以在 Scala 中做这样的事情吗?
最佳答案
如果你只关心这两个条件,你可以有这样的事情
if(ua.isEmpty || ua.contains('curl')) false
如果你想要更多的案例,你可以这样做
ua match{
case _ if(ua.isEmpty) => false
case _ if(ua.contains('curl') => false
case _ => //return whatever you want if none of the above is true
}
或者使用传统的 if else
if(ua.isEmpty)
false
else if(ua.contains('curl')
false
else
// return whatever you want
请注意,如果您不添加最后的 else
或最后的 case _=>
,则返回类型将为 Any
并且不是 bool 值
关于scala - 在 Scala 中编写级联 if 语句的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56271137/