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

时间:2019-05-23 08:32:31

标签: 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中做类似的事情吗?

3 个答案:

答案 0 :(得分:6)

如果您只关心这两个条件,您可以拥有这样的东西

browse.setOnClickListener(new View.OnClickListener() {
   public void onClick(View v) {
      String escapedQuery = null;
      resume = true;
      countDownTimer.cancel(); //I have no idea where to resume
      try {
          escapedQuery = URLEncoder.encode(begriff2, "UTF-8");
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }

      Uri uri = Uri.parse("http://www.google.com/#q=" + escapedQuery);
      Intent intent = new Intent(Intent.ACTION_VIEW, uri);
      startActivity(intent);
   }
});

如果您想获得更多案例,可以执行以下操作

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(ua.isEmpty) false else if(ua.contains('curl') false else // return whatever you want 或最后一个else,则返回类型将是case _=>而不是Any

答案 1 :(得分:2)

除了酒神的答案:

您还可以使用要检查的type中的object-使其更具可读性。

如果您是uaList

ua match{
     case Nil => false
     case l if l.contains('curl') => false
     case _ => true
    }

如您所见,我还做了其他一些小的调整:

    不需要()中的
  • 参数if
  • 我更喜欢为匹配的值命名,并在if
  • 中使用该名称

答案 2 :(得分:1)

如果您正在使用Scala,建议您将ua ua: Option[String]与Options一起使用。

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 = // "String" or ""
val result = if (ua.contains('curl') || ua.isEmpty || ua != "") false else // What you want

您不应使用val ua: String = null,答案是here