Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading