Returning a when needs else, but using just when (without return) doesn't

When I do this, it’s okay:

fun foo(amount: Int) {
         when (amount) {
            in Int.MIN_VALUE..0 -> doStuff1()
            in 1..9 -> doStuff2()
            in 10..Int.MAX_VALUE -> doStuff3()
        }
}

When I do this, compiler says that I need an else branch:

fun foo(amount: Int): Int {
         return when (amount) {
            in Int.MIN_VALUE..0 -> doStuff1()
            in 1..9 -> doStuff2()
            in 10..Int.MAX_VALUE -> doStuff3()
        }
}

so it only let’s me further if I do this, which doesn’t look nice:

fun foo(amount: Int): Int {
         return when (amount) {
            in Int.MIN_VALUE..0 -> doStuff1()
            in 1..9 -> doStuff2()
            in 10..Int.MAX_VALUE -> doStuff3()
            else -> { -1 } //which will never be called, or?
        }
}

Could some please explain why this is the case?

1 Like

Kotlin doesn’t yet have integer range analysis to determine how much you’ve covered, unlike some languages like Scala. Simple fix:

fun foo(amount: Int): Int {
         return when (amount) {
            in Int.MIN_VALUE..0 -> doStuff1()
            in 1..9 -> doStuff2()
            else -> doStuff3()
        }
}
1 Like

Thanks a lot. The basic problem (at least why I consider it as a problem) is having an else, but sure this can work :slight_smile: Is there a site where we can check the Kotlin backlog and even further do you know if it’s in the backlog at all?

1 Like

It is not perfect, but you can always do this:

else -> error()

You can add an error message or a code comment, that this line should never be invoked.

3 Likes

Their backlog is all on Youtrack
I think it’s not currently a goal. I think Roman once said (but I’m not sure) that it’s currently not a goal for Kotlin since it’ll hit compiler performance and won’t add much usefulness.

1 Like