扔在Kotlin的操作员
在kotlin中重写下面的代码将会是一个更优雅的方式。
if (xList.isEmpty()) { throw SomeException("xList was empty") }
我们有一个throwif操作符或什么的?
在Kotlin库中,有些函数会在输入无效时抛出异常,例如requireNotNull(T?, () -> Any)
。 你可以参考这些函数,并写一个类似的函数来处理空列表,如果你想。
public inline fun <T> requireNotEmpty(value: List<T>?, lazyMessage: () -> Any): List<T> { if (value == null || value.isEmpty()) { val message = lazyMessage() throw IllegalArgumentException(message.toString()) } else { return value } } //Usage: requireNotEmpty(xList) { "xList was empty" }
或者简单地使用require(Boolean, () -> Any)
:
require(!xList.isEmpty()) { "xList was empty" }
我喜欢使用takeIf
标准函数来验证,在elvis操作符的基础上 ,它给出了这个:
xList.takeIf{ it.isNotEmpty() } ?: throw SomeException("xList was empty")
我不知道标准库中的函数,但是您可以轻松地自己做到这一点:
/** * Generic function, evaluates [thr] and throws the exception returned by it only if [condition] is true */ inline fun throwIf(condition: Boolean, thr: () -> Throwable) { if(condition) { throw thr() } } /** * Throws [IllegalArgumentException] if this list is empty, otherwise returns this list. */ fun <T> List<T>.requireNotEmpty(message: String = "List was empty"): List<T> { throwIf(this.isEmpty()) { IllegalArgumentException(message) } return this } // Usage fun main(args: Array<String>) { val list: List<Int> = TODO() list.filter { it > 3 } .requireNotEmpty() .forEach(::println) }
原始代码紧凑,透明和灵活。 固定例外的乐趣可能更为紧凑。
infix fun String.throwIf(b: Boolean) { if (b) throw SomeException(this) } "xList was empty" throwIf xList.isEmpty()
- Int和Int类型参数的标识符相等已被弃用
- Android studio 2.3:无法初始化类org.jetbrains.kotlin.android.actions.NewKotlinActivityAction
- Kotlin + Intelij + HtmlUnit:使用提供的参数不能调用下列函数
- Android – Kotlin – 对象必须声明为抽象或实现抽象成员
- Room Persistance Library在插入和删除时致命错误11(SIGEGV)崩溃
- 使用Anko访问活动的视图
- 在浏览器中运行Kotlin HTML Builder
- Jooq事务:如果在事务中抛出异常,连接不会释放到池中
- 不能实现接口kotlin