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
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.
+ 2
Lisa Tibor Santa Thanks!
+ 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.