Home > Software engineering >  Type mismatch on throw line in Kotlin?
Type mismatch on throw line in Kotlin?

Time:01-11

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?

CodePudding user response:

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

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