scala - 在 Scala 中编写级联 if 语句的更好方法?

标签 scala

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/

相关文章:

java - 运行文件选择器的 Scala 类

Scala 理解 : How to Recover and Continue If a Future Fails

scala - Spark – 连接第一行匹配条件

json - 如何使用 argonaut 解析可选的自定义字段?

scala - 使用 Scala 和 Play WS 将内联图像添加到 Mailgun 电子邮件

scala - Play Framework 2.4.1 : How to get configuration values just after configuration file has been loaded

有限范围的 Scala LazyList

algorithm - 通过位掩码进行二进制搜索?

scala - 如何编写具有上下文边界的一流函数,可以在使用现场干净地调用?

java - 为 Log4j Appender 运行 Kafka-0.8.1 时出错