Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The ! (logical NOT) operator is a unary prefix operator that performs logical negation on a boolean expression. It evaluates to true if the operand is false, and false if the operand is true.
val isFalse = !true

Under the Hood: Operator Overloading

Kotlin implements operators as syntactic sugar for specific member or extension function calls. The compiler translates the ! prefix operator into a call to the not() function.
val isTrue = true

// Syntactic sugar
val a = !isTrue

// Compiler translation
val b = isTrue.not()

Nullability Constraints

Because the ! operator translates to a standard method call (not()), it is bound by Kotlin’s null safety rules. You cannot apply the ! operator directly to a nullable Boolean? receiver. Doing so results in a compilation error because the underlying not() call is not safe.
val flag: Boolean? = true

// Compilation Error: Reference has a nullable type 'Boolean?'
// val inverted = !flag 

// Correct: Explicit safe call to the underlying function
val invertedSafe = flag?.not() 

Custom Type Overloading

Because the operator is resolved via the not() function, it is not restricted to primitive booleans. You can apply the ! operator to any custom class by defining an operator fun not() member or extension function. The return type of the overloaded function is not required to be a Boolean.
class BinaryState(val state: Int) {
    // Overloading the ! operator
    operator fun not(): BinaryState {
        return BinaryState(if (state == 0) 1 else 0)
    }
}

val high = BinaryState(1)
val low = !high // Resolves to high.not()

Precedence

As a unary prefix operator, ! has a higher precedence than multiplicative, additive, and logical binary operators (like && and ||). When combined with binary operations, the negation is applied to the immediate right-hand operand before the binary operation is evaluated, unless overridden by parentheses.
val a = true
val b = false

// Evaluates as (!a) && b
val result = !a && b 

// Evaluates the binary expression first, then negates the result
val resultGrouped = !(a && b) 
Master Kotlin with Deep Grasping Methodology!Learn More