kotlinkotlin-when

Incompatible error with When statement in Kotlin


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
    }

Solution

  • 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
        }