Kotlin 为空的判断

1、?: kotlin.run

注意:必须先写run 带出Kotlin。

//对象为空判断
var chapterBean = list.find { it.chapter_id == currentChapterId}
                        chapterBean?.let { it1 ->
                           //chapterBean不为null执行正常逻辑....
                        } ?: kotlin.run{
                            //chapterBean为null执行其它逻辑....

2、?: run

注意:必须先写run 。

      //对象为空判断
        var chapterBean = list.find { it.chapter_id == currentChapterId }
        chapterBean?.let { it1 ->
            //chapterBean不为null执行正常逻辑....
        } ?: run {
            //chapterBean为null执行其它逻辑....

3、也可以多层判断

注意:?.let { }只能过滤null,不能过滤空字符串。

      //对象为空判断
        var chapterBean = list.find { it.chapter_id == currentChapterId }
        chapterBean?.let { it1 ->
            //返回最后一行
            //chapterBean不为null执行正常逻辑....
        }?.also {
            //返回本身
        }?.apply {
            //返回本身
        }?.run {
            //返回最后一行
        } ?: run {
            //chapterBean为null执行其它逻辑....

4、kotlin 中?.为什么不能过滤空字符串?

在 Kotlin 中,使用 ?. 运算符可以在对象不为空时调用其属性或方法,否则返回 null。但是,它并不会过滤空字符串,因为空字符串仍然是一个有效的字符串对象,它的长度为 0。如果要过滤空字符串,可以使用 filter() 函数或者判断字符串是否为空字符串来实现。