Booleans
The Boolean type represents logical values: true and false.
Use Boolean values in functions that answer yes-or-no questions, and in the while, if, and when conditions.
Declare a Boolean variable
To declare a Boolean variable, assign it true or false.
You can specify the Boolean type explicitly or let Kotlin infer it from the value:
If a value can be null, use Boolean?:
Produce Boolean values
You can use comparison expressions and functions to produce Boolean values:
You can use the results in conditions and other expressions as well:
Boolean operations
Kotlin provides operators and infix functions for working with Boolean values. You can use them to invert a Boolean value or combine multiple Boolean values into a single result.
Negation (NOT)
The NOT operator inverts a Boolean value.
To use NOT, place the ! operator before a Boolean value:
Logical AND
The AND operator returns true only if both operands are true.
To use logical AND, place the && operator between operands:
Logical OR
The OR operator returns true if at least one operand is true.
To use logical OR, place the || operator between operands:
Exclusive OR (XOR)
The exclusive OR (XOR) operation returns true if the operands have different values.
To use XOR, write xor between operands:
Operator precedence
If an expression contains multiple logical operations and no parentheses to specify the evaluation order, Kotlin applies precedence rules. Operations with higher precedence are evaluated before operations with lower precedence.
For the Boolean operations described in this section, the precedence order is as follows:
!xor(and other infix functions)&&||
In the following example, the compiler evaluates && before ||:
To make evaluation order explicit, use parentheses:
Boolean in conditions
if, when, and while evaluate Boolean expressions to direct program flow.