Alek Sung
Alek Sung

Reputation: 61

Why can't Kotlin infer return type of a Boolean expression using ==?

From what I understand, Kotlin should be able to infer the return type of a function based on the last expression used in the function body.

fun returnInt() {
    42 + 24
}

However, when I create a function expecting the result of an equality (==) operation such as:

fun returnBoolean() {
    someBool == otherBool
}

I get the following warning:

Unused equals expression

I can resolve this by adding a return type and a return statement:

fun returnBoolean(): Boolean {
    return someBool == otherBool
}

But I was just wondering why returnBoolean() gets an 'Unused equals expression' and returnInt() does not.

Upvotes: 0

Views: 209

Answers (1)

Alek Sung
Alek Sung

Reputation: 61

Silly me.

Kotlin is able to infer such statements using an equals sign in the function declaration:

fun returnInt() =
    42 + 24


fun returnBoolean() =
    someBool == otherBool


As a beginner to Kotlin, I find it interesting that returnInt() does not get a warning, but if you try to use it during runtime (in my case I passed it as an argument to java.lang.String.format), it will throw an exception.

Upvotes: 1

Related Questions