Leave a rating/review
In this challenge, you’re going to fortify your knowledge of when expresions.
For this, you have to use a when expression to return in which century a year of your choosing is.
You have to cover at least three past centuries, and for other cases, return a predefined message.
Then print out the message!
That’s it! :] Now pause the video, and try to solve the challenges. Then when you’re done, hit the play button, and check my solution!
Hint: Use ranges for the century checks!
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.
I’ll start off by choosing a year:
val year = 1984
Then create a parameterized when statement:
when (year) {
}
This allows you to match the year to values easily. Add the following cases to match the centuries:
when (year) {
in 2000..2022 -> "21st century!"
in 1900..1999 -> "20th century!"
in 1800..1899 -> "19th century!"
else -> "This was looong ago!"
}
Because we’re currently in 2022, you don’t have to check the future! :]
Now, store the result of this when in a value like so:
val message = when (year) {
in 2000..2022 -> "21st century!"
in 1900..1999 -> "20th century!"
in 1800..1899 -> "19th century!"
else -> "This was looong ago!"
}
And finally, print it out:
println(message)
Run the project, and you should see message printed out!
You used range checks for the value, and an else case to cover all the years or range spans you didn’t cover.
You also used the when as an expression to return a value and store it in a constant you printed out.
Good job!