kotlinidioms

kotlin KT-28061 for details for null safety on compiler


why cant I just

return s?.let{ it }?: {throw IllegalStateException("you got something screwed up...")}

for a function? from my understanding the compiler should be able to detect we either have a non null or an exception no?

fun foo(): String{
    val s: String? = null
    return s?.let{ it }?: {throw IllegalStateException("you got something screwed up...")}
}

or

fun foo(): String{
    val s: String? = null
    s?.let{
        return it
    }?: {throw IllegalStateException("you got something screwed up...")}
}

Solution

  • The compiler should be able to detect we either have a non null or an exception

    That's not what you have: You return either a String or a function that throws an exception, specificly a funtion of type () -> Nothing. The latter is not compatible with the return type of foo, hence the compile error.

    You probably meant to return this:

    return s?.let { it } ?: throw IllegalStateException("you got something screwed up...")
    

    Note that I removed the curly braces that wrapped the exception in a function: Now it is either a String that is returned or an exception that is thrown, not a function that throws an exception.