如何将“throw”放置在辅助函数中但仍然具有空安全性?

Mar*_*.H. 2 kotlin

我想将 a 包装throw在辅助函数中,用于日志记录等目的。


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
}
Run Code Online (Sandbox Code Playgroud)

问题:kotlin抱怨类型不匹配:

Type mismatch.
Required: Email
Found: Email?
Run Code Online (Sandbox Code Playgroud)

我猜编译器不知道throwAndNotice总是会抛出异常。如果我内联该throwAndNotice方法,它可以工作,但会导致大约十几个方法重复。

有没有办法告诉编译器“以下方法总是抛出”?或者还有另一种惯用的方法来处理这个问题?我不想求助于!!.

Swe*_*per 7

让它返回Nothing。这表明它永远不会返回(抛出异常或无限循环):

private fun throwAndNotice(err: CustomError): Nothing {
    NewRelic.noticeError(err)
    throw err
}
Run Code Online (Sandbox Code Playgroud)

您可以在标准库中看到执行此操作的其他示例,例如TODO()error()

旁注(正如 dey 在评论中提到的):

空检查可以使用?:如下重写:

return emailAddress ?: throwAndNotice(...)
Run Code Online (Sandbox Code Playgroud)