Negate condition of an if-statement
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
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)
- ->
- eg:
- any (boolean like) value
- eg:
someStr.isEmpty
- ->
!someStr.isEmpty
- no need redundant parentheses
- ->
- eg: