simha
simha

Reputation: 574

How to write an If-Else loop involving multiple conditions in an idiomatic Scala way?

I'm a Scala noob and trying to write the following piece of validation code in a Scala idiomatic way.

How do I make use of Options and case-match in such a scenario ? Or is it not possible to avoid a null check here ?

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

Upvotes: 0

Views: 202

Answers (2)

bottaio
bottaio

Reputation: 5093

That's exactly what XOR does

val flag = c1 == null ^ c2 == null

As @jwvh mentioned, would be great to avoid nulls in Scala as well.

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

val flag = o1.isDefined ^ o2.isDefined

Note, in both examples you don't need to use var.

Upvotes: 3

jwvh
jwvh

Reputation: 51271

First off, we like to avoid nulls by nipping them off as early as possible.

val o1 = Option(/*code that retrieved/created c1*/)
val o2 = Option(/*code that retrieved/created c2*/)

Then code that "manipulates" mutable variables is a bad idea, but as you didn't include that part we can't offer better solutions for it.

val flag = o1.fold(o2.nonEmpty)(_ => o2.isEmpty) &&
              //other code continues that calculates flag value

Upvotes: 3

Related Questions