如果Kotlin中的运算符抛出 [英] throw if operator in Kotlin

查看:79
本文介绍了如果Kotlin中的运算符抛出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What would be a more elegant way to rewrite the below code in kotlin.

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

我们有throwif运算符之类的吗?

Do we have a throwif operator or something?

推荐答案

我喜欢使用

I like to use the takeIf standard function to validate, with elvis operator addition, it gives this:

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


我必须补充一点,在大多数情况下,我需要的是 IllegalArgumentException ,使用


I have to add that in most cases an IllegalArgumentException is what I need, and it is simpler to just use require.
In cases that we need an IllegalStateException, we can rather use check.

另请参见: checkNotNull requireNotNull 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆