Meet the Kotlin Programming Language

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

Lesson 05: Use Functions

Demo

Episode complete

Play next episode

Next
Transcript

Open the Starter project in the 05-use-functions 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 functions.

Sticking to our theme of legendary music lyrics, you’ll create a function to print the lyrics of yet another chart-topper!

Type the following snippet in your scratch file:

// 1
fun playBabyShark(count: Int) {
  // 2
  for (i in 1..count) {
    println("Baby Shark, doo-doo, doo-doo, doo-doo")
  }
  println("Baby shark")
}

// 3
playBabyShark(3)

The function above prints the lyrics to Baby Shark. In the snippet above:

  1. You created a playBabyShark function that accepts a count argument of type Int.
  2. The function body prints the lyric the number of times specified by count.
  3. You then call the playBabyShark function with value 3.

As shown below, you can modify this function to make it more flexible with default arguments:

fun playBabyShark(count: Int = 3, shark: String = "Baby") {
    for (i in 1..count) {
        println("$shark Shark, doo-doo, doo-doo, doo-doo")
    }
    println("$shark shark")
}

playBabyShark()
playBabyShark(shark = "Mommy")

In the revised snippet above, you:

  • Provided a default value of count
  • Added another parameter to accept shark as an argument

When the function is called without specifying any arguments, it prints the default lyrics. Otherwise, it prints the lyrics for the shark specified.

Wasn’t that fun?

It’s time to kick things up a notch and tie all your learnings so far. You’ll use two functions to create another function that simulates a vending machine:

  1. A function to accept a snack name and return the cost of the snack.
  2. A function to accept a snack name and some coins. This function will either dispense the snack or print an error if enough coins aren’t inserted.

In your scratch file, type the following:

// Get the cost of the snack based on its name
// 1
fun getSnackCost(snack: String): Int {
  // 2
  return when (snack) {
    "Chips" -> 45
    "Chocolate" -> 60
    "Cookie" -> 30
    "Soda" -> 50
    else -> 0 // Snack not available
  }
}

In the snippet above, you:

  1. Created a getSnackCost function that accepts a snack string as input and returns an integer value.
  2. Return the number of coins required for each snack based on the type of snack you return.

Next, type the following in your scratch file below the getSnackCost function:

// Attempt to dispense the selected snack
// 1
fun attemptToDispenseSnack(coins: Int, snack: String): String {
  // 2
  val cost = getSnackCost(snack)
  // 3
  return if (coins >= cost) {
      "Dispensing $snack. Enjoy your snack!"
  } else {
      "Not enough coins inserted. $snack costs $cost cents."
  }
}

// 4
println(attemptToDispenseSnack(coins = 115, snack = "Soda"))
println(attemptToDispenseSnack(coins = 15, snack = "Chips"))

In this snippet, you:

  1. Created an attemptToDispenseSnack that accepts the coins and snack as arguments.
  2. It calls the getSnackCost function to get the cost of the snack.
  3. Based on the cost of the snack and the coins available, it either dispenses the snack or prints an error.
  4. You then called the attemptToDispenseSnack function with different values to simulate both flows.

That ends this demo. Continue with the lesson for a summary.

See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion