Incompatible error with When statement in Kotlin

51 views Asked by At

The Below code gives me the "Incompatible types:Boolean and Int". Not sure what might be the issue.

 var votersAge = 17
 var cardEligibility = when(votersAge)
    {
        (votersAge > 18) -> true
        (votersAge <= 18) -> false
        else -> false
    }
1

There are 1 answers

0
David Soroko On BEST ANSWER

You can think of when(votersAge) as a expression that in this case evaluates to an Int. In when's body, the logic branches according to the value of the expression and so expects an Int , you however provide a Boolean.

when expression/statement is documented here

Try this:

 val votersAge = 17
 val cardEligibility = when
    {
        votersAge > 18 -> true
        else -> false
    }

or alternatively, this:


    val cardEligibilityw = when (votersAge)
    {
        in 0..18 -> false
        else -> true
    }