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

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 15. Learn more Loop Features Next episode: 17. Challenge: Use When Expressions

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

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

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}")
}