gpt4 book ai didi

kotlin - 如果Kotlin中的运算符抛出

转载 作者:行者123 更新时间:2023-12-02 11:48:32 26 4
gpt4 key购买 nike

用kotlin重写下面的代码会是一种更优雅的方法。

if (xList.isEmpty()) {
throw SomeException("xList was empty")
}

我们有throwif运算符或其他东西吗?

最佳答案

我喜欢使用 takeIf 标准函数进行验证,并添加elvis operator,它可以实现以下功能:

xList.takeIf { it.isNotEmpty() } ?: throw SomeException("xList was empty")


我必须补充一点,在大多数情况下,我需要的是 IllegalArgumentException,仅使用 require 更为简单。
在需要 IllegalStateException的情况下,我们宁可使用 check
另请参阅: checkNotNullrequireNotNullerror

关于kotlin - 如果Kotlin中的运算符抛出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47222982/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com