扔在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()