In Kotlin,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.
if is an expression that evaluates a boolean condition and returns a value based on the executed branch. Because it yields a value, Kotlin does not possess a traditional ternary operator (condition ? then : else); the if expression natively fulfills this role.
Syntax Mechanics
Theif construct functions either as a standard control flow statement or as an expression assigned to a variable.
As a Statement:
When used as a statement, the if construct does not require an else branch. It directs control flow without returning a value.
if construct evaluates to a value.
Evaluation Rules
When utilizingif as an expression, specific compiler rules apply:
- Exhaustiveness: The expression must be exhaustive. An
elsebranch is strictly mandatory so the compiler can guarantee a value is returned regardless of the condition’s outcome. - Block Evaluation: If a branch is enclosed in a block
{ ... }, the value of that branch is determined by the last expression within the block. Preceding statements are executed for their side effects. - Type Resolution: The compiler determines the return type of the
ifexpression by finding the least upper bound (common supertype) of the types returned by all branches.
Block Expression Syntax
When branches require multiple operations, the final expression in the block dictates the return value:Type Inference Behavior
If the branches of anif expression return different types, the Kotlin compiler infers the closest common supertype. If the if is used as a statement (not assigned or returned), its evaluated type is implicitly Unit.
Smart Casting
A critical semantic feature of Kotlin’sif construct is its integration with the compiler’s control flow analysis to enable Smart Casting. When an if condition checks a variable’s type using the is operator or verifies nullability (!= null), the compiler automatically casts the variable to the target type within the lexical scope of the corresponding branch.
Master Kotlin with Deep Grasping Methodology!Learn More





