Kotlin判空的各种操作

个人原创,转载请注明出处:https://www.jianshu.com/p/e7049cef9431

If not null

val files = File("Test").listFiles()
println(files?.size)

If not null or else

val files = File("Test").listFiles()
println(files?.size ?: "empty")

If not null and true

if (someObject?.status == true)  doThis()

someObject?.takeIf{ it.status }?.apply{ doThis() }

If not null and true or else

if (someObject?.status == true)  {
    doThis()
}else {
    doThat()
}

someObject?.takeIf{ it.status }?.apply{ doThis() } ?: apply{ doThat() }

if not null 赋值

val objA = ...
val objB = ...
objB.value = objA.value ?: objB.value

if null 赋值

val objA = ...
val objB = ...
objB.value = objB.value ?: objA.value

if null 执行一个语句

val values = ……
val email = values["email"] ?: throw IllegalStateException("Email is missing!")

参考

https://www.kotlincn.net/docs/reference/idioms.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容