Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/30.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
如何以惯用的Scala方式编写包含多个条件的If-Else循环?_Scala_Functional Programming - Fatal编程技术网

如何以惯用的Scala方式编写包含多个条件的If-Else循环?

如何以惯用的Scala方式编写包含多个条件的If-Else循环?,scala,functional-programming,Scala,Functional Programming,我是一个Scala noob,试图以Scala惯用的方式编写下面的验证代码 在这种情况下,如何使用选项和案例匹配?或者在这里不可能避免空检查吗 var flag = True // set flag to true when exactly 1 of (c1,c2) is present if (c1 == null and c2 == null) or (c1 != null and c2 != null){ flag = False } // other code continu

我是一个Scala noob,试图以Scala惯用的方式编写下面的验证代码

在这种情况下,如何使用选项和案例匹配?或者在这里不可能避免空检查吗

var flag = True

// set flag to true when exactly 1 of (c1,c2) is present
if (c1 == null and c2 == null) or (c1 != null and c2 != null){
    flag = False
}

// other code continues that manipulates flag

首先,我们喜欢通过尽可能早地删除空值来避免空值

val o1 = Option(/*code that retrieved/created c1*/)
val o2 = Option(/*code that retrieved/created c2*/)
那么,操纵可变变量的代码是一个坏主意,但由于您没有包括这一部分,我们无法提供更好的解决方案

val flag = o1.fold(o2.nonEmpty)(_ => o2.isEmpty) &&
              //other code continues that calculates flag value
这正是XOR所做的

正如@jwvh所提到的,在Scala中避免空值也很好

val o1 = Option(c1) // turns null into None
val o2 = Option(c2)

val flag = o1.isDefined ^ o2.isDefined
注意,在这两个示例中,您不需要使用var。

没有if循环。这被称为有条件的。
val o1 = Option(c1) // turns null into None
val o2 = Option(c2)

val flag = o1.isDefined ^ o2.isDefined