Jeff Hu Jeff Hu - 1 year ago 131
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") }

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download