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

你可能感兴趣的:(Kotlin判空的各种操作)