Why doesn't my code work? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why doesn't my code work?

fun main(args: Array<String>) { var age = readLine()!!.toInt() var result = when { age <= 11 -> "Child" age == 12 && age <= 17 -> "Teen" age == 18 && age <= 64 -> "Adult" age => 65 -> "Senior" age < 0 -> "Invalid age" } println(result) } The result is: error

15th Mar 2023, 2:48 PM
Artem Riabchikov
Artem Riabchikov - avatar
3 Answers
+ 2
If you try to run the code in the code playground, you can also look at the full error message. A when expression must be exhaustive. If the cases are not enums, you need an 'else' branch at the end. Mind the order of your conditions. If you write <=11 first, then <0 at the end will never be evaluated, because negative numbers have already satisfied <=11. => is not a proper comparison operator. And finally a number cannot be equal to 12 AND smaller or equal to 17 at the same time, unless it's exactly 12.
15th Mar 2023, 3:21 PM
Tibor Santa
Tibor Santa - avatar
+ 2
16th Mar 2023, 7:44 AM
Artem Riabchikov
Artem Riabchikov - avatar
+ 1
For example, look at the 2nd condition: age == 12 && age <= 17 is only true when age = 12. You probably mean age >= 12 && age <= 17 Same thing in the 3rd condition.
15th Mar 2023, 3:18 PM
Lisa
Lisa - avatar