Null Safety
前情提要:? .? !! 一堆有的沒有的鬼符號搞得頭暈
筆記一下
Kotlin 官方:http://kotlinlang.org/docs/reference/null-safety.html
can not hold null:
var a: String = "abc"
a = null // compilation error
declare a variable as nullable string, written String?:
var b: String? = "abc"
b = null // ok
Now, if you call a method or access a property on a, it's guaranteed not to cause an NPE, so you can safely say:
val l = a.length
But if you want to access the same property on b, that would not be safe, and the compiler reports an error:
val l = b.length // error: variable 'b' can be null
Checking for null in conditions
Safe Calls
b?.length
bob?.department?.head?.name
Such a chain returns null if any of the properties in it is null.
To perform a certain operation only for non-null values, you can use the safe call operator together with let:
val listWithNulls: List<String?> = listOf("A", null)
for (item in listWithNulls) {
item?.let { println(it) } // prints A and ignores null
}
Elvis Operator
?:
val l = b?.length ?: -1
The !! Operator
Safe Casts
val aInt: Int? = a as? Int
Collections of Nullable Type
If you have a collection of elements of a nullable type and want to filter non-null elements, you can do so by using filterNotNull:
val nullableList: List<Int?> = listOf(1, 2, null, 4)
val intList: List<Int> = nullableList.filterNotNull()