Home > Mobile >  How can I place `throw` inside helper-functions but still have null-safety?
How can I place `throw` inside helper-functions but still have null-safety?

Time:08-09

I want to wrap a throw in a helper-function, for logging purposes and such.


private fun chooseEmailAddress(user: UserProfile): EmailAddress {
    val emailAddress = user.emailAddresses.find {
        true // some business logic
    }
    if (emailAddress == null) {
        throwAndNotice(CustomError(
            message = "No Email Address found.",
        ))
    }
    return emailAddress
}

private fun throwAndNotice(err: CustomError) {
    NewRelic.noticeError(err)
    throw err
}

The problem:kotlin complains about a type-mismatch:

Type mismatch.
Required: Email
Found: Email?

I guess the compiler does not know that throwAndNotice always throws. If I inline the throwAndNotice method, it works, but it leads to duplication in about a dozen methods.

Is there a way I can tell the compiler "the following method always throws"? Or is there another idiomatic way to deal with this issue? I don't want to resort to !!.

CodePudding user response:

Make it return Nothing. This indicates that it will never return (either throw an exception or infinite loop):

private fun throwAndNotice(err: CustomError): Nothing {
    NewRelic.noticeError(err)
    throw err
}

You can see other examples of doing this in the standard library, like TODO() and error().

Side note (as mentioned by dey in the comments):

The null check can be rewritten using ?: like this:

return emailAddress ?: throwAndNotice(...)
  • Related