如何以惯用的Scala方式编写包含多个条件的If-Else循环?
我是一个Scala noob,试图以Scala惯用的方式编写下面的验证代码 在这种情况下,如何使用选项和案例匹配?或者在这里不可能避免空检查吗如何以惯用的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
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