本文介绍了如果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?
推荐答案我喜欢使用 takeIf 标准函数进行验证,并使用猫王运算符另外,它给出了以下内容:
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 ,使用 要求 .在需要 IllegalStateException 的情况下,我们可以使用 检查 .
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 ,错误
更多推荐
如果Kotlin中的运算符抛出
发布评论