kotlin - 如何将 `throw` 放入辅助函数中但仍然具有空安全性?

我想在辅助函数中包装一个 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
}

问题:kotlin 提示类型不匹配:

Type mismatch.
Required: Email
Found: Email?

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

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

最佳答案

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

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

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

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

可以使用 ?: 重写 null 检查,如下所示:

return emailAddress ?: throwAndNotice(...)

关于kotlin - 如何将 `throw` 放入辅助函数中但仍然具有空安全性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73274963/

相关文章:

delphi - 组件是特定类 - 在 BPL 结构中不起作用

reactjs - 使用 React Router 将可选查询参数添加到动态路径

c++ - 创建其他对象时如何使用同一个对象实例?

c++ - 子类调用父复制分配而不是移动分配?

c - gcc中的 '-Wextra'和 '-pedantic'有什么区别?

python - 如何按列导出数据框以分隔 csv 文件?以及如何将不同数据框中的列附加到分离的 c

python - 如果数字在 Pandas 的指定范围内,如何返回值

javascript - ECMA脚本 : What does `status` mean in S

google-cloud-platform - 我无法让 google cloud function

caching - Aerospike 为特定字段设置到期日期