Control Flow: Making Decisions in Code
8 min read
Control Flow: Making Decisions in Code ๐ง
Welcome, budding Kotlin developer! So far, you've been writing code that executes line by line, from top to bottom. But what if you want your code to make decisions? What if you want it to react differently based on certain conditions? That's where Control Flow comes in. It's like the brain of your program, allowing it to think and choose its path.
Imagine you're building a simple ticket booking system. You need to check if the user is old enough to watch a particular movie. If they are, you issue a ticket. If not, you politely decline. Control flow statements are the tools that let you implement this kind of logic.
If-Else Expressions: Returning Values from Conditions ๐ฆ
The Problem: You need your program to do one thing if a condition is true and another thing if it's false.
The Solution: The if-else expression is your fundamental decision-making tool. It evaluates a condition and executes a block of code if the condition is true. Optionally, it can execute a different block of code if the condition is false.
In Kotlin, if-else is an expression, which means it can return a value. This is a powerful feature that can make your code more concise.
Syntax:
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}Example: A Simple Age Check
Let's revisit our movie ticket scenario.
fun canWatchMovie(age: Int) {
if (age >= 18) {
println("You are old enough to watch this movie. Enjoy!")
} else {
println("Sorry, this movie is for viewers 18 and older.")
}
}
fun main() {
canWatchMovie(25) // Output: You are old enough to watch this movie. Enjoy!
canWatchMovie(16) // Output: Sorry, this movie is for viewers 18 and older.
}Using if-else as an Expression
Now, let's see how we can use if-else to return a value.
fun getTicketPrice(isStudent: Boolean): Int {
val price = if (isStudent) {
10 // Discounted price for students
} else {
15 // Regular price
}
return price
}
fun main() {
val studentPrice = getTicketPrice(true)
println("The ticket price for a student is $$studentPrice.") // Output: The ticket price for a student is $10.
val regularPrice = getTicketPrice(false)
println("The regular ticket price is $$regularPrice.") // Output: The regular ticket price is $15.
}In this example, the if-else block directly determines the value of the price variable. This is a common and idiomatic way to write such logic in Kotlin.
A Funny Exaggeration: Imagine your code is a bouncer at a very exclusive club. The if condition is the bouncer checking the guest's ID. If the ID is valid (true), they get in. If not (false), the else block sends them home to their cat. Without if-else, everyone gets in, and soon you have a club full of toddlers and grandmas crashing the party. Chaos!
The 'When' Expression: Kotlin's Switch on Steroids ๐
The Problem: You have a situation with multiple possible outcomes based on the value of a single variable. Using a long chain of if-else if statements can become clumsy and hard to read.
The Solution: The when expression is Kotlin's powerful and flexible replacement for the traditional switch statement found in other languages. It's more readable, less error-prone, and can handle a wider variety of cases.
Syntax:
when (variable) {
value1 -> // block of code for value1
value2 -> // block of code for value2
else -> // block of code if none of the above match
}Example: Handling User Roles
Imagine you're building a system with different user roles, and you need to display a different greeting for each.
fun getGreeting(role: String): String {
return when (role) {
"Admin" -> "Welcome, administrator! You have full access."
"Editor" -> "Hello, editor! You can create and edit content."
"Viewer" -> "Hi there, viewer! You can see all the public content."
else -> "Welcome, guest! Please log in for more options."
}
}
fun main() {
println(getGreeting("Admin"))
println(getGreeting("Viewer"))
println(getGreeting("Subscriber"))
}What makes when so special?
- No
breakneeded: Unlikeswitchin many other languages, you don't need to add abreakstatement at the end of each case. It's a common source of bugs that Kotlin cleverly avoids. - Can be used as an expression: Just like
if-else,whencan return a value, making your code cleaner. - Combining multiple values: You can check for multiple values in a single branch.
- Using ranges and conditions: You can use ranges and arbitrary expressions as conditions.
Example: Advanced when
Let's look at a more complex example that showcases the power of when.
fun describeNumber(number: Int) {
when (number) {
0 -> println("It's zero!")
1, 2, 3 -> println("It's a small positive number.")
in 4..10 -> println("It's a number between 4 and 10.")
!in 11..20 -> println("It's not between 11 and 20.")
else -> println("It's some other number.")
}
}
fun main() {
describeNumber(0)
describeNumber(2)
describeNumber(7)
describeNumber(25)
}Industry Practice: In professional Kotlin development, when is heavily favored over long if-else if chains for its readability and compile-time checks that ensure you've handled all possible cases (especially with enum classes or sealed classes).
For Loops and Ranges: Iterating with Elegance ๐ถโโ๏ธ
The Problem: You have a collection of items (like a list of names or numbers), and you need to perform an action on each item in the collection.
The Solution: for loops are the standard way to iterate over anything that can be iterated upon. Kotlin's for loop, combined with its powerful ranges, makes this process incredibly intuitive and clean.
Syntax:
for (item in collection) {
// do something with item
}Example: Printing a List of Names
fun main() {
val names = listOf("Alice", "Bob", "Charlie")
for (name in names) {
println("Hello, $name!")
}
}Iterating with Ranges
Ranges are a unique feature of Kotlin that allows you to easily specify a sequence of numbers.
1..5: Includes numbers from 1 to 5 (inclusive).1 until 5: Includes numbers from 1 to 4 (exclusive of 5).5 downTo 1: A range that counts backward.1..10 step 2: A range that increments by 2.
Example: Using Ranges in for loops
fun main() {
println("Counting from 1 to 5:")
for (i in 1..5) {
print("$i ") // Output: 1 2 3 4 5
}
println("\n\nCounting from 1 until 5:")
for (i in 1 until 5) {
print("$i ") // Output: 1 2 3 4
}
println("\n\nCounting down from 5 to 1:")
for (i in 5 downTo 1) {
print("$i ") // Output: 5 4 3 2 1
}
println("\n\nCounting from 1 to 10 with a step of 2:")
for (i in 1..10 step 2) {
print("$i ") // Output: 1 3 5 7 9
}
}Real-life Scenario: Imagine you are a mail carrier and you have a list of addresses on your route (a collection). You go to each address one by one to deliver the mail. A for loop is like you, the mail carrier, systematically visiting each address in your route.
While Loops, Break, and Continue ๐
The Problem: You need to repeat a block of code as long as a certain condition is true, but you don't know in advance how many times it will need to run. Or, you might need to exit a loop early or skip a specific iteration.
The Solution: while loops and their companions break and continue give you more fine-grained control over your loops.
while loop: Executes a block of code as long as its condition is true.
Syntax:
while (condition) {
// code to be executed
}Example: A Simple Countdown
fun main() {
var countdown = 5
while (countdown > 0) {
println(countdown)
countdown--
}
println("Blast off!")
}do-while loop: Similar to a while loop, but it guarantees that the block of code is executed at least once before the condition is checked.
Syntax:
do {
// code to be executed
} while (condition)break and continue
break: Immediately terminates the nearest enclosing loop.continue: Skips the current iteration of the nearest enclosing loop and proceeds to the next one.
Example: Using break and continue
Imagine we are looking for the first even number in a list, but we want to ignore the number 4.
fun main() {
val numbers = listOf(1, 3, 4, 5, 6, 7, 8)
for (number in numbers) {
if (number == 4) {
println("Skipping the number 4.")
continue // Skip to the next iteration
}
if (number % 2 == 0) {
println("Found the first even number (that is not 4): $number")
break // Exit the loop
}
}
}Under the Hood: When your Kotlin code is compiled, these high-level control flow structures are translated into lower-level bytecode instructions that the Java Virtual Machine (JVM) understands. This process is highly optimized by the compiler.
๐ Extra Reading
- Official Kotlin Documentation on Control Flow: https://kotlinlang.org/docs/control-flow.html
- Kotlin Ranges and Progressions: https://kotlinlang.org/docs/ranges.html
Challenge
Challenge: Theme Park Ticket Calculator
You need to implement the calculateTicketCost function in Kotlin. This function will calculate the total ticket cost for a group of visitors based on their ages, the day of the week, and a set of pricing rules.
Function Signature:fun calculateTicketCost(ages: List<Int>, dayOfWeek: String): Double
Requirements:
- The base price for a single adult ticket is
30.0. All other prices are derived from this base price. - Iterate through the
ageslist. Your loop must use thecontinuekeyword to skip any invalid age entries (ages less than 0 or greater than 110). These invalid entries should not be included in any calculations, including the group size count. - Inside the loop, use a
whenexpression with ranges to determine the cost for each valid age. The pricing tiers are:- 0-4 years (inclusive): Free (0% of base price)
- 5-12 years (inclusive): 50% of the base price.
- 13-17 years (inclusive): 80% of the base price.
- 18-64 years (inclusive): 100% of the base price.
- 65-110 years (inclusive): 75% of the base price.
- After calculating the subtotal for all valid visitors, you must apply a final adjustment. This adjustment is based on group size and the day of the week.
- Use an
if-elseexpression to determine the final price:- If the number of valid visitors is 10 or more, apply a 15% discount to the subtotal.
- Otherwise (if the group is smaller than 10), check if the
dayOfWeekis "Saturday" or "Sunday". If it is, apply a 20% surcharge to the subtotal. - Note: The group discount and the weekend surcharge are mutually exclusive. A large group does not pay a weekend surcharge even on a weekend.
- The function must return the final calculated total cost as a
Double.
Expected result
Your function should be a complete implementation that correctly calculates the total cost according to all the specified rules. The logic must use a for loop for iteration, continue for skipping invalid data, a when expression with ranges for age-based pricing, and an if-else expression for the final discount/surcharge calculation.
For example, given the input ages = listOf(10, 35, 70, 3, -5, 120, 36, 16, 40, 66) and dayOfWeek = "Saturday", your function should:
- Count 8 valid visitors (skipping -5 and 120).
- Calculate the subtotal for the 8 valid visitors.
- Since the group size is less than 10, it should apply the 20% weekend surcharge to the subtotal.
As another example, for ages = listOf(10, 10, 10, 10, 10, 30, 30, 30, 30, 30) and dayOfWeek = "Sunday", your function should:
- Count 10 valid visitors.
- Calculate the subtotal for the 10 visitors.
- Since the group size is 10, it should apply the 15% group discount and not apply the weekend surcharge.