Programming in Kotlin: Fundamentals

Aug 9 2022 Kotlin 1.6, Android 12, IntelliJ IDEA CE 2022.1.3

Part 2: Manage Control Flow

16. Simplify Code with When Expressions

Lesson Complete

Play Next Lesson
Next
Save for later
About this episode
See versions
See forum comments
Cinema mode Mark as Complete Download course materials
Previous episode: 15. Learn more Loop Features Next episode: 17. Challenge: Use When Expressions

This video was last updated on Aug 9 2022

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.

You learned how If/Else expressions are also a part of managing the control flow. Sometimes you have a lot of cases in such an expression, and the logic gets complicated, or just too long to cover with just if/else statements.

val age = 23
when(age) {

}
when(age) {
 23 -> println("Close to a quarter century!")
 25 -> println("Quarter century!")
 else -> {
   println("Don't know your age!")
 }
}
when(age) {
  in 0..12 -> println("Still a young human")
  in 13..19 -> println("Teenager")
  in 20..29 -> println("In your twenties")
  in 30..39 -> println("In your thirties")
  in 40..49 -> println("In your forties")
  else -> println("You're a wise person :]")
}
val message = when(age) {
  in 0..12 -> "Still a young human"
  in 13..19 -> "Teenager"
  in 20..29 -> "In your twenties"
  in 30..39 -> "In your thirties"
  in 40..49 -> "In your forties"
  else -> "You're a wise person :]"
}

println(message)
val email = "mail@mail.com"
val password = "iLoveKotlin!"
when {
}
when {
  email.isEmpty() -> {
    println("You need to choose an email!")
  }
}
when {
  ...
  
  "@" !in email -> {
    println("Your email is invalid :[")
  }
}
when {
  ...
  
  password.isEmpty() -> {
    println("You need to choose a password!")
  }

  password.length < 10 -> {
    println("Password not strong enough :[")
  }
}
when {
  ...
  
  else -> {
   println("Email length: ${email.length}, " +
      "Password length: ${password.length}")
  }
}
when {
  email.isEmpty() -> println("You need to choose an email!")

  "@" !in email -> println("Your email is invalid :[")

  password.isEmpty() -> println("You need to choose a password!")

  password.length < 10 -> println("Password not strong enough :[")

  else -> println("Email length: ${email.length}, " +
  "Password length: ${password.length}")
}