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

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Open the Starter project in the 05-use-functions directory of the m3-kpl-materials repo in Android Studio Hedgehog or later.

// 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)
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")
// 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
  }
}
// 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"))
See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion