android-kotlin
/

Kotlin Control Flow – Expressions and Pattern Matching

Last Sync: Today

On this page

6
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

android-kotlin

Kotlin Control Flow – Expressions and Pattern Matching

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.

  1. 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.

KOTLINRead-only
1
// Traditional style
val max: Int
if (a > b) { max = a } else { max = b }

// Idiomatic Kotlin (The 'Ternary' replacement)
val maxValue = if (a > b) a else b

// Multi-line expression (the last line is the return value)
val status = if (isModelLoaded) {
    println("System Ready")
    "ACTIVE"
} else {
    "PENDING"
}

  1. 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.

KOTLINRead-only
1
fun processWidget(obj: Any) = when (obj) {
    1 -> println("Numeric ID")
    "Button", "Icon" -> println("Interactive Element")
    is String -> println("String of length ${obj.length}")
    in 1..10 -> println("Priority Range")
    !is Int -> println("Not an integer")
    else -> println("Unknown Type")
}

// Using 'when' as a replacement for complex if-else-if chains
when {
    project.isCloud -> syncToCloud()
    project.isLocal -> saveToDisk()
    else -> discardChanges()
}

  1. 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.

KOTLINRead-only
1
// Inclusive range (1 to 5)
for (i in 1..5) print(i)

// Exclusive range (0 to 9)
for (i in 0 until 10) print(i)

// Stepping and downward ranges
for (i in 10 downTo 0 step 2) print(i)

// Iterating over a collection with index
for ((index, value) in widgetList.withIndex()) {
    println("Item at $index is $value")
}

  1. 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

FeatureKotlinDart (Flutter)
IfExpression (Returns value)Statement Only
Switch Equivalentwhen (Expression)switch (Statement)
Ternary OperatorNone (Use If-Expression)Supported (a ? b : c)
Iterationfor (item in list)for (var item in list)
Ranges1..10 / until / stepN/A (Use List.generate)
Type Checkis / !isis / is!

Test Your Knowledge

Q1
of 3

Which Kotlin structure serves as a more powerful replacement for the traditional switch statement?

A
switch
B
case
C
when
D
choose
Q2
of 3

What is the result of using a range like '1 until 5' in a loop?

A
1, 2, 3, 4, 5
B
1, 2, 3, 4
C
0, 1, 2, 3, 4
D
5, 4, 3, 2, 1
Q3
of 3

True or False: Kotlin does not have a ternary operator (condition ? true : false).

A
True
B
False

Frequently Asked Questions

Does 'when' require an 'else' branch?

If you use 'when' as an expression (assigning it to a variable), the compiler must be sure all cases are covered. If you are checking an Enum or a Sealed Class, and you cover all cases, 'else' is not needed. Otherwise, 'else' is mandatory.

How do I break out of nested loops in Kotlin?

Kotlin supports 'Labels'. You can mark a loop with a label (e.g., 'loop@') and then use 'break@loop' to exit specifically from that outer loop, which is much cleaner than using boolean flags.

Can I use 'when' without an argument?

Yes! When used without an argument, it acts as a more readable replacement for an if-else-if chain. Each branch condition must evaluate to a Boolean.

Previous

kotlin variables

Next

kotlin functions

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.