Kotlin If with NOT Operator
The condition of If-statement can be negated using Logical NOT Operator !
. In this tutorial, we will learn how to use Logical NOT Operator (!) in the boolean condition/expression of Kotlin If-statement.
The following is a simple scenario where the condition is negated with Logical NOT Operator.
if ( !condition ) { //code }
The truth table for the result of the expression !condition
is
condition | !condition |
---|---|
true | false |
false | true |
Example
In the following Kotlin program, we have an integer value in a
. We shall check if this integer is not even.
The expression to check if a
is even is a%2 == 0
.
The expression to check if a
is not even is !(a%2 == 0)
.
Main.kt
fun main(args: Array<String>) { val a = 13 if ( !(a%2 == 0) ) { print("$a is not even.") } }
Output
13 is not even.
Conclusion
In this Kotlin Tutorial, we learned how to use Logical NOT Operator in If-statement’s boolean condition, with the help of example programs.