TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
?: operator, commonly referred to as the Elvis operator, is a binary null-coalescing operator in Kotlin. It evaluates its left-hand operand and returns it if it resolves to a non-null value; if the left-hand operand evaluates to null, it evaluates and returns the right-hand operand.
Syntax
Evaluation Mechanics
1. Short-Circuit Evaluation The?: operator evaluates lazily. The right-hand operand is strictly evaluated if and only if the left-hand operand resolves to null. If the left side is non-null, the right side is completely ignored, preventing potential side effects or unnecessary computation.
?: expression based on the least upper bound (lowest common supertype) of the non-nullable type of the left operand and the type of the right operand.
- If the left operand is of type
T?and the right operand is of typeT, the resulting expression is guaranteed to be of the non-nullable typeT. - If the left operand is of type
T?but the right operand is of a nullable typeU?, the resulting expression evaluates to a nullable type.
?: operator has lower precedence than infix function calls and arithmetic operators (both additive and multiplicative), but higher precedence than comparison (relational) and equality operators. Consequently, expressions on the right-hand side involving arithmetic operators are evaluated together before the ?: operator is applied.
Nothing Type
In Kotlin, control flow statements such as return and throw are expressions that evaluate to the Nothing type. Because Nothing is a subtype of all other types in Kotlin’s type system, these expressions are syntactically valid as the right-hand operand of the ?: operator.
If the left operand is null, the Nothing expression is evaluated, immediately terminating the current control flow path. The compiler understands that if execution continues past this statement, the left operand could not have been null. Consequently, if the left operand is a reference eligible for smart casting (such as a local val or a function parameter), the compiler automatically smart-casts it to its non-nullable counterpart for the remainder of the scope. The resulting value of the ?: expression itself is inferred as a non-nullable type.
Master Kotlin with Deep Grasping Methodology!Learn More





