如果Kotlin中的运算符抛出

编程入门 行业动态 更新时间:2024-10-09 15:17:33
本文介绍了如果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中的运算符抛出

本文发布于:2023-11-09 04:00:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1571343.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:抛出   运算符   Kotlin

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!