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

在Scala中编写级联if语句的更好方法?,scala,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; } 有什么建议我们可以在S

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
或最终的
案例=>
,则返回类型将是
Any
,而不是
Boolean

,作为Dionysis答案的补充:

您还可以使用要检查的
对象的
类型
,以使其更具可读性

在您的情况下,如果
ua
列表

ua match{
     case Nil => false
     case l if l.contains('curl') => false
     case _ => true
    }
如您所见,我还做了一些其他小调整:

  • 如果不需要
    中的参数
    ()
  • 我更喜欢命名匹配的值,并在
    if

如果您使用的是Scala,我建议将选项与ua一起使用
ua:Option[String]

val ua: Option[String] = // Some("String") or None
val result = ua match {
 case Some(x: String) if x.contains("curl") => false
 case Some(x) => // What you want
 case None => false
 case _ => // Error
}
如果要使用
If
,则应使用
ua:String
(不推荐)


您不应该使用
val ua:String=null
如果(ua.isEmpty | | ua.contains(“curl”))返回false,则答案是
,因为这是一个表达式,因此不必使用
返回
val ua: String = // "String" or ""
val result = if (ua.contains('curl') || ua.isEmpty || ua != "") false else // What you want