在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