Programming in Kotlin: Fundamentals

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

Part 2: Manage Control Flow

17. Challenge: Use 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: 16. Simplify Code with When Expressions Next episode: 18. Conclusion

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.

In this challenge, you’re going to fortify your knowledge of when expresions.

Challenge:

Use a when expression to return a `String` that tells which century an arbitrary year is from.

Cover at least the last three centuries, and return “This was looong ago!” for others.

Then print out the returned value. 

Hint: Use Ranges for year comparison.
val year = 1984
when (year) {

}
when (year) {
  in 2000..2022 -> "21st century!"
  in 1900..1999 -> "20th century!"
  in 1800..1899 -> "19th century!"
  else -> "This was looong ago!"
}
val message = when (year) {
  in 2000..2022 -> "21st century!"
  in 1900..1999 -> "20th century!"
  in 1800..1899 -> "19th century!"
  else -> "This was looong ago!"
}
println(message)