Control Flow as Expressions
In Kotlin, if and when are expressions: they can return a value that can be assigned to a variable. As an Architect, you should use this to replace the ternary operator (which Kotlin does not have) and to make your native Android logic more functional and less imperative.
- If-Expression
Because if returns a value, you can use it directly in assignments. This reduces the scope of variables and makes the intent of your code clearer.
- The 'When' Expression (Power Switch)
The when expression is Kotlin's highly evolved version of the switch statement. It is significantly more flexible, allowing you to check types, ranges, and multiple conditions in a single branch. For Revochamp, this is the perfect tool for handling different widget types coming from the AI.
- For Loops and Ranges
Kotlin simplifies iteration using Ranges. You don't write traditional for (int i=0; i<10; i++) loops. Instead, you use the in operator with ranges like 1..10 or 0 until list.size.
- While and Do-While
The while and do-while loops in Kotlin behave exactly as they do in Dart and Java. Use these when the number of iterations is not known beforehand, such as waiting for a background AI process to finish.
Control Flow Comparison
| Feature | Kotlin | Dart (Flutter) |
|---|---|---|
| If | Expression (Returns value) | Statement Only |
| Switch Equivalent | when (Expression) | switch (Statement) |
| Ternary Operator | None (Use If-Expression) | Supported (a ? b : c) |
| Iteration | for (item in list) | for (var item in list) |
| Ranges | 1..10 / until / step | N/A (Use List.generate) |
| Type Check | is / !is | is / is! |