Meet the Kotlin Programming Language

Apr 10 2024 · Kotlin 1.9, Android 14, Android Studio Hedgehog

Lesson 04: Leverage Control Flows

Demo

Episode complete

Play next episode

Next
Transcript

Open the Starter project in the 04-leverage-control-flows directory of the m3-kpl-materials repo in Android Studio Hedgehog or later.

Wait for the project to finish building.

Create a new scratch file in the com.yourcompany.android.meetkotlin package.

In this lesson, you’ll practice working with the different control flow constructs available in Kotlin.

If else lets you structure your code and execute certain blocks based on the evaluated value. In your snippet, type the following:

// 1
val age = 1

// 2
if (age < 12 ) {
 // 3
 println("You can't vote")
} else if (age < 18) {
 println("You can vote soon")
} else {
 print("You can vote")
}

The snippet above:

  1. Creates a variable age and assigns it a value of 1.
  2. Uses an if-else block to check the age.
  3. Prints the body of the block that evaluates to true.

If you have multiple conditions to evaluate, it often makes sense to use when instead of an if-else ladder to enhance readability.

Type the following snippet in your scratch file:

// 1
println("Welcome to Kotlin Snack Corner!")
println("Please select an item by entering the number:")
println("1. Burger\n2. Pizza\n3. Sandwich\n4. Fries")

// 2
val choice = 4

// 3 & 4
val preparationTime = when (choice) {
    1 -> "Burger will take 10 minutes to prepare."
    2 -> "Pizza will take 15 minutes to prepare."
    3 -> "Sandwich will take 5 minutes to prepare."
    4 -> "Fries will take 7 minutes to prepare."
    else -> "Sorry, we don't have that item on our menu."
}

// 5
println(preparationTime)

The snippet above simulates an order-taking program for a restaurant. In this program, you:

  1. Printed the menu options to the console.
  2. Created a variable choice with a value of 4.
  3. Then used a when clause to create branches for all possible menu options.
  4. Evaluated the expression to assign a message to the preparationTime variable
  5. Finally, printed the preparationTime to the console.

Kotlin offers three looping constructs to repeat an operation based on a specified condition. They are:

  • for loop
  • while loop
  • do while loop

Type the following snippet in your scratch file:

var lyric = "Haters gonna"

for (i in 1..5) {
    lyric += " hate"
}

println(lyric)

In this fun snippet, you loop over a range of numbers from 1 to 5 and for each iteration, you append the string “hate” to the lyric. At the end of the loop, you print the lyric to the famous Taylor Swift song.

For loop lets you iterate over a given range, a collection, or an array. If you want to iterate based on conditions, you can use the while or do-while loop.

Type the following in your scratch file:

var counter = 10
while (counter >= 0) {
    println("T-$counter")
    counter--
}

println("We have lift off \uD83D\uDE80")

This snippet will run a counter starting from 10 and countdown until 0. At each iteration, it prints the current value of the counter and decrements the value.

The do-while loop is similar in nature, except it first executes its body and then checks for the condition.

The snippet above can be rewritten using a do-while loop as follows:

var counter = 10
do {
    println("T-$counter")
    counter--
} while (counter >= 0)
println("We have lift off \uD83D\uDE80")
See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion