Câu hỏi phỏng vấn Kotlin
Câu hỏi

Explain the null safety in Kotlin

Câu trả lời

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:

Nullable Types

To declare a variable as nullable, you append a ? to the type, like this:

kotlin Copy
var name: String? = null

Now, name can hold either a String value or null.

Safe Call Operator (?.)

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.

kotlin Copy
val length = name?.length

Here, length will be null if name is null.

Elvis Operator (?:)

The Elvis operator provides a concise way to handle nullable values...

middle

middle

Gợi ý câu hỏi phỏng vấn

middle

What are coroutines in Kotlin?

expert

What is the difference between Java field and Kotlin property?

junior

What is the idiomatic way to remove duplicate strings from array?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào