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 xor operator in Kotlin is an infix function that performs an Exclusive OR operation. When applied to integer types, it executes a bitwise operation comparing corresponding bits of two numeric values. When applied to boolean types, it executes a logical operation evaluating to true strictly when the operands possess different truth values. Unlike C-family languages (such as Java or C++) that use the caret symbol (^), Kotlin implements xor as a named function declared with the infix modifier.

Syntax

Because xor is an infix function, it can be invoked using either infix notation or standard method invocation:
// Infix notation (idiomatic)
val result = a xor b

// Standard function call
val result = a.xor(b)

Bitwise xor (Integer Types)

When operating on integral types (Int, Long, Short, Byte, and their unsigned counterparts), xor compares the binary representations of the operands bit by bit. It returns 1 if the corresponding bits are different, and 0 if they are the same. Bitwise Truth Table:
  • 0 xor 0 = 0
  • 0 xor 1 = 1
  • 1 xor 0 = 1
  • 1 xor 1 = 0
Code Example:
val a = 0b1010  // Decimal 10
val b = 0b1100  // Decimal 12

val result = a xor b 
// Execution:
//   1010
//   1100
//   -
//   0110  -> Decimal 6
Note: Since Kotlin 1.5, Byte and Short types have their own strict bitwise functions (e.g., infix fun Byte.xor(other: Byte): Byte). These operations return a result of the same type without implicitly promoting the operands to Int.

Logical xor (Boolean Type)

When operating on Boolean types, xor evaluates the logical state of the operands. It returns true if one operand is true and the other is false. If both operands share the same state, it returns false. Boolean Truth Table:
  • false xor false = false
  • false xor true = true
  • true xor false = true
  • true xor true = false
Code Example:
val conditionA = true
val conditionB = false

val result1 = conditionA xor conditionB // Evaluates to true
val result2 = conditionA xor true       // Evaluates to false

Operator Precedence

In Kotlin’s operator precedence hierarchy, all named infix functions (including xor, and, or, shl, shr, ushr) share the exact same precedence level. They have lower precedence than arithmetic operators (+, -, *, /, %) but higher precedence than logical operators (&&, ||). Because all named infix functions share the same precedence, they are evaluated strictly left-to-right (left-associative).
val result = 2 + 3 xor 4 shl 1

// Evaluates as:
// 1. Arithmetic addition: (2 + 3) -> 5
// 2. Left-to-right infix: 5 xor 4 -> 1
// 3. Left-to-right infix: 1 shl 1 -> 2
// Final result: 2
Master Kotlin with Deep Grasping Methodology!Learn More