Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sql-server-2005/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
if和elseif内部的scala多重条件_Scala - Fatal编程技术网

if和elseif内部的scala多重条件

if和elseif内部的scala多重条件,scala,Scala,有没有更好的方法在scala中编写以下代码: val x = r.get(c.CITY) val y = r.get(c.COUNTRY) val z = r.get(c.DIVISION) val a = r.get(c.RESIDENT) if (x == 1 || y == 1 || z == 1 ) { "apple" } else if (a.nonEmpty) { "mango" } else { "banana" } 你可以玩模式匹配 val res = (x, y

有没有更好的方法在scala中编写以下代码:

val x = r.get(c.CITY)
val y = r.get(c.COUNTRY)
val z = r.get(c.DIVISION)
val a = r.get(c.RESIDENT)

if (x == 1 || y == 1 || z == 1 ) {
  "apple"
} else if (a.nonEmpty) {
  "mango"
} else {
  "banana"
}

你可以玩模式匹配

val res = (x, y, z, a) match {
  case (1, _, _, _) | (_, 1, _, _) | (_, _, 1, _) => false
  case (_, _, _, a) if a.nonEmpty => false
  case _ => None
}
甚至使用提取器对象来定义条件


object FalseTupleComparison {
  def unapply(t: ( Int, Int,  Int, A)): Option[Boolean] = Some(t._1 != 1 && t._2 != 1 && t._3 != 1)
}
object EmptyTupleComparison {
  def unapply(t: ( Int, Int,  Int, A)): Option[Boolean] = Some(t._4.nonEmpty)
}

val res2 = (x, y, z, a) match {
  case FalseTupleComparison(res) => res
  case EmptyTupleComparison(res) => res
  case _ => None
}


您的
if
/
else
语句链是表达此逻辑的最清晰的方式,因为所涉及的条件范围不同

您可以使用
匹配
,但它只是让它变得不那么清晰

a match {
  case _ if x == 1 || y == 1 || z == 1 => "apple"
  case Some(_) => "mango"
  case _ => "banana"
}

如果支票数量增加,可选择:

if (List(x,y,z).contains(1)) "apple"
else if (a.nonEmpty) "mango"
else "banana"

作为scala的新手,我只是想弄明白,如果存在上述情况,我们如何才能以更好的方式编写它?@DmytroMitin当我点击upvote按钮时,它说我的回购协议不到15份,所以我不能这么做。好吧,我是为你做的:)@abhi即使没有15份声誉,你也可以接受答案: