Skip to main content
In Kotlin, Boolean is a fundamental data type representing a logical entity that can possess one of exactly two values: true or false. On the JVM, a non-nullable Boolean is compiled to a primitive boolean to optimize memory and performance, while a nullable Boolean? is boxed as a java.lang.Boolean object reference. To maintain primitive memory optimization for arrays on the JVM, Kotlin provides the BooleanArray type, which compiles to a primitive boolean[]. In contrast, using a standard Array<Boolean> results in an array of boxed objects (Boolean[]).

Declaration and Instantiation

Boolean variables and arrays can be declared explicitly or inferred by the compiler.

Logical Operators

Kotlin provides standard logical operators for Boolean types. The conjunction and disjunction operators utilize short-circuit evaluation, meaning the right-hand operand is only evaluated if the left-hand operand does not definitively determine the outcome.
  • || (Logical OR): Returns true if at least one operand is true. Short-circuits if the left operand is true.
  • && (Logical AND): Returns true if both operands are true. Short-circuits if the left operand is false.
  • ! (Logical NOT): A unary operator that inverts the boolean value.

Infix Functions

In addition to standard operators, Kotlin provides infix functions for boolean arithmetic. Unlike && and ||, these infix functions do not short-circuit; both operands are always evaluated.
  • and: Performs a logical AND operation.
  • or: Performs a logical OR operation.
  • xor: Performs a logical exclusive OR operation. Returns true strictly when the operands evaluate to different values.

Nullability and Equality

When working with a nullable Boolean?, standard logical operators (&&, ||, !) cannot be used directly without prior null-checking or unwrapping. However, structural equality operators (==, !=) are null-safe.

String Conversion

The Kotlin String API provides extension functions to parse string values into Boolean types. These functions offer varying levels of strictness regarding case sensitivity and format validation.
  • toBoolean(): Case-insensitive and lenient. Returns true if the string is equal to "true" (ignoring case), and safely returns false for any other string, including invalid formats.
  • toBooleanStrict(): Strictly case-sensitive. Returns true for "true" and false for "false", but throws an IllegalArgumentException for any other value.
  • toBooleanStrictOrNull(): Strictly case-sensitive, but returns null instead of throwing an exception for invalid formats.
Tired of Poor Kotlin Skills? Fix That With Deep Grasping!Learn More