Inequality within "when" statement outputs error

79 Views Asked by At

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.

1

There are 1 best solutions below

2
On BEST ANSWER

Unfortunately you can't use when's argument in when's cases explicitly. So you can adjust your code like this:

var string_age = when(age) {
    in 0..11 -> "Child"
    in 12..17 -> "Teen"
    in 18..64 -> "Adult"
    else -> {
        if (age > 64) {
            "Senior"
        } else {
            "Invalid age"
        }
    }
}

Or like this, moving age out of when and using it explicitly in all cases

var string_age = when {
    age in 0..11 -> "Child"
    age in 12..17 -> "Teen"
    age in 18..64 -> "Adult"
    age > 64 -> "Senior";
    else -> "Invalid age"
}

Or you can use following trick with range

in 65..200 -> "Senior" instead of age > 64 -> "Senior". 200 years is big enough for a person's lifespan ;)