Kotlin判空的各种操作(替换if else)

时间:2025-02-08 15:33:24

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{  }?.apply{ doThis() }

If not null and true or else

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

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

if not null 赋值

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

if null 赋值

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

if null 执行一个语句

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

参考

/docs/reference/