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 == operator in Kotlin evaluates structural equality. It determines whether the data or state of two objects is equivalent by delegating to the underlying equals() method, rather than checking if they occupy the same memory address. Unlike Java, where == evaluates referential equality for objects, Kotlin’s == is an inherently null-safe wrapper around the equals() function.

Compiler Translation

When the Kotlin compiler encounters the == operator, it translates the expression into a null-safe method call.
a == b
At compile time, this expression is translated to:
a?.equals(b) ?: (b === null)

Execution Mechanics

  1. Null Safety: The operator guarantees null safety without throwing a NullPointerException. If the left-hand operand (a) is null, the safe call operator (?.) yields null. The Elvis operator (?:) then evaluates the right-hand side, checking if b is also null using the referential equality operator (===).
  2. Method Dispatch: If a is not null, the operator invokes a.equals(b). This relies on the class’s specific implementation of override fun equals(other: Any?): Boolean.
  3. Default Behavior: If a class does not explicitly override equals() (and is not a data class), the operator falls back to the implementation inherited from Any, which performs a referential equality check.
  4. Primitive Optimization: When comparing Kotlin types that map to JVM primitives (such as Int, Double, or Boolean), the compiler optimizes the == operator directly into the JVM’s primitive == bytecode instruction. This bypasses the equals() method entirely, eliminating boxing and unboxing overhead.
  5. Floating-Point Comparison: When comparing Float or Double types statically typed as their specific types, == follows the IEEE 754 standard (e.g., NaN == NaN is false). However, if the operands are statically typed as Any or Comparable, == falls back to the equals() implementation, which enforces a total order (e.g., NaN == NaN is true).

Structural vs. Referential Equality

Kotlin strictly separates value comparison from memory address comparison using two distinct operators:
  • == (Structural Equality): Evaluates if the values or states are equivalent via equals().
  • === (Referential Equality): Evaluates if both references point to the exact same object instance in the heap.
// Structural equality check
val isStructurallyEqual = (obj1 == obj2) 

// Referential equality check
val isReferentiallyEqual = (obj1 === obj2) 
Master Kotlin with Deep Grasping Methodology!Learn More