sak
sak

Reputation: 1298

How to use "When" with any condition expression?

I am trying to use when with one condition expression like this:

fun getStringLength(s: Int){
    when(s < 5){

    }
}

The code gets compiled but when i try to give the body to this when block like:

fun getStringLength(s: Int){
    when(s < 5){
       in 1..5 -> println("It is less than 5")
    }
}

It gives me an error of: "Error:(13, 7) Type inference failed. The value of the type parameter T should be mentioned in input types (argument types, receiver type or expected type). Try to specify it explicitly. Error:(13, 7) Type mismatch: incompatible types of range and element checked in it"

So how do i make it work?

Upvotes: 0

Views: 157

Answers (1)

Bracadabra
Bracadabra

Reputation: 3659

When you write s < 5 it is calculated to boolean value, that's why your conditions should be true, false or else.

fun getStringLength(s: Int){
    when(s < 5){
        true -> println("It is less than 5")
        false -> println("It is NOT less than 5")
    }
}

To use range in, please, try this one:

fun getStringLength(s: Int){
    when(s){
       in 1..5 -> println("It is less than 5")
    }
}

Upvotes: 2

Related Questions