Here I have a program which assigns the value of a variable based on different conditions:
fun main(args: Array<String>) {
var age = readLine()!!.toInt()
var string_age = when(age) {
in 0..11 -> "Child"
in 12..17 -> "Teen"
in 18..64 -> "Adult"
age > 64 -> "Senior"
else -> "Invalid age"
}
print(string_age)
}
However, the inequality "age > 64" returns "incompatible types: Boolean and Int". What must I do in order to use an inequality within a "when" statement.
Unfortunately you can't use
when
's argument inwhen
's cases explicitly. So you can adjust your code like this:Or like this, moving
age
out ofwhen
and using it explicitly in all casesOr you can use following trick with range
in 65..200 -> "Senior"
instead ofage > 64 -> "Senior"
. 200 years is big enough for a person's lifespan ;)