[Kotlin] Nullable Variables

In Kotlin, it helps to avoid null reference, which means by default you cannot assign null value to any variable;

But if you do want to assign null to a variable, you can do:

var strnull: String? = null

Safe guard:

just like Typescript, you can use ? to type safe check:

var strnull: String? = null
print(strnull?.length)  // null

If strnull is null, then print null, if not null, then print its length

!!:

If you are sure that your variable is not null, then you can do:

var str = "wan"
print(str!!.length) // 3

If 'str' is null, then it will throw NullPointerExpection error

原文地址:https://www.cnblogs.com/Answer1215/p/13796061.html