Type mismatch on throw line in Kotlin?

Please help me understand the following error in Kotlin: I have the following function

fun getSomething(): Something {
    return loginContext.user()?.let {
        // user is logged in
        return Something()
    } ?: {
        // user is not logged in
        throw UnauthorizedException()
    }
}

and IntelliJ tells me

Type mismatch.
Required: Something
Found: () → Nothing

Coming from Java I find this a bit confusing because when I throw an exception there is nothing to return. How can there be a type mismatch?

>Solution :

I believe you may write it like this (using expression body)

fun getSomething(): Something = loginContext.user()
    ?.let { Something() }
    ?: throw UnauthorizedException()

Leave a Reply