Jeff Hu Jeff Hu - 6 months ago 41
Scala Question

Negate condition of an if-statement

if I want to do sth 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") }


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. ie: x==0 to make it behave exactly like the first code example above.