Explain the null safety in Kotlin
Explain the null safety in Kotlin
Kotlin's null safety is a set of features designed to help developers avoid the dreaded NullPointerException (NPE) that often plagues Java programs. In Kotlin, variables are non-nullable by default, meaning they cannot hold a null value unless explicitly declared as nullable.
Here are the key aspects of null safety in Kotlin:
To declare a variable as nullable, you append a ? to the type, like this:
var name: String? = null
Now, name
can hold either a String value or null.
The safe call operator allows you to safely access properties or call methods on a nullable reference without causing an NPE. If the reference is null, the expression returns null instead of throwing an exception.
val length = name?.length
Here, length
will be null if name
is null.
The Elvis operator provides a concise way to handle nullable values...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào