Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negate condition of an if-statement

Tags:

scala

If I want to do something like:

if (!(condition)) { }

What is the equivalent expression in Scala? Does it looks like?

if (not(condition)) { }

For example, in C++, I can do:

bool condition = (x > 0)
if(!condition){ printf("x is not larger than zero") }

EDIT: I have realized that Scala can definitely do the same thing as I asked. Please go ahead and try it.

like image 559
Jeff Hu Avatar asked Oct 16 '16 12:10

Jeff Hu


2 Answers

In Scala, you can check if two operands are equal (==) or not (!=) and it returns true if the condition is met, false if not (else).

if(x!=0) {
    // if x is not equal to 0
} else {
    // if x is equal to 0
}

By itself, ! is called the Logical NOT Operator.

Use it to reverse the logical state of its operand.

If a condition is true then Logical NOT operator will make it false.

if(!(condition)) {
    // condition not met
} else {
    // condition met
}

Where !(condition) can be

  • any (logical) expression
    • eg: x==0
      • -> !(x==0)
  • any (boolean like) value
    • eg: someStr.isEmpty
      • -> !someStr.isEmpty
        • no need redundant parentheses
like image 133
jrbedard Avatar answered Sep 17 '22 20:09

jrbedard


if (! condition) { doSomething() }

condition in the above if expression can be any expression which evaluates to Boolean

for example

val condition = 5 % 2 == 0

if (! condition) { println("5 is odd") }

!= is equivalent to negation of ==

if (x != 0) <expression> else <another expression>

Scala REPL

scala> if (true) 1
res2: AnyVal = 1

scala> if (true) 1
res3: AnyVal = 1

scala> if (true) 1 else 2
res4: Int = 1
like image 24
pamu Avatar answered Sep 21 '22 20:09

pamu