Kotlin相較于java的一大優(yōu)勢就是可以減少空指針的出現坎匿,變量的type需要指定是否能為空盾剩,不帶?的type不能為空
var a: String = "abc"
a = null // compilation error
var b: String? = "abc"
b = null // ok
不為空的變量可以調用方法替蔬,但是為空的變量使用前顯式需要檢查是否為空
val l = a.length //合法
val l = b.length // 不合法
檢查是否為空
- option1
val l = if (b != null) b.length else -1
或者
if (b != null && b.length > 0) {
print("String of length ${b.length}")
} else {
print("Empty string")
}
- option2
safe call 操作符
b?.length
如果b不為空告私,返回 b.length,如果b為空承桥,返回null
safe call可以和let一起使用驻粟,只對非空元素進行操作
val listWithNulls: List<String?> = listOf("A", null)
for (item in listWithNulls) {
item?.let { println(it) } // prints A and ignores null
}
Elvis 操作符
?:
如果符號左邊的表達式不為空,則返回左邊的表達式凶异,否則返回右邊的表達式
val l = b?.length ?: -1
如果b?.length
不為空蜀撑,則返回它,如果為空剩彬,返回-1
return
和throw
可以放在elvis操作符的右邊
fun foo(node: Node): String? {
val parent = node.getParent() ?: return null
val name = node.getName() ?: throw IllegalArgumentException("name expected")
// ...
}
!!操作符
b!!酷麦,如果b不為空,則返回b喉恋,如果b為空沃饶,則throw NullPointerException母廷。
val l = b!!.length
使用filterNotNull
來過濾集合中空元素