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

What is the idiomatic way to deal with null able values, referencing or converting them?

Câu trả lời

Here is an idiomatic way to deal with nullable values in Kotlin:

Safe Call Operator ?.

The safe call operator ?. is used to safely access properties or call methods on a nullable reference. If the reference is not null, the operation is performed, otherwise null is returned. For example:

kotlin Copy
val length = person?.name?.length()

This will return the length of the name string if person and person.name are not null, otherwise it will return null.

Elvis Operator ?:

The Elvis operator ?: is used to provide a default value if a nullable expression evaluates to null. For example:

kotlin Copy
val name = person?.name ?: "Anonymous"

This will assign the value of person.name to name if it is not null, otherwise it will assign the default value "Anonymous".

Non-Null Assertion !!

The non-null assertion !! is used to assert that a nullable expression is not null. If the expression is null, it will throw a NullPointerException. For example:

ko... Copy
middle

middle

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

senior

Why is there no static keyword in Kotlin?

junior

How to correctly concatenate a String in Kotlin?

senior

What are Object expressions in Kotlin and when to use them?

Bình luận

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

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