[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

posted @ 2020-10-11 01:56  Zhentiw  阅读(109)  评论(0编辑  收藏  举报