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

When would you use Elvis operator in Kotlin?

Câu trả lời

The Elvis operator (?:) in Kotlin is used to provide a concise way to handle nullable values. It allows you to specify a default value to be used when a nullable expression evaluates to null. Here are some common scenarios where you might use the Elvis operator:

Handling Nullable Values

When you have a nullable variable or expression and want to provide a fallback value in case it is null, you can use the Elvis operator. For example:

kotlin Copy
val name: String? = null
val displayName = name ?: "Anonymous"
println(displayName) // Output: Anonymous

In this case, if name is null, the Elvis operator will return the default value "Anonymous".

Simplifying Null Checks

The Elvis operator can help simplify null checks in your code. Instead of using an if-else statement to handle null values, you can use the Elvis operator to provide a more concise solution. For example:

kotlin Copy
val length = name?.length ?: 0
println(length) // Output: 0

Here, if name is not null, the length of the string is returned; otherwise, the default value 0 is used.

Chaining Elvis Operators

You can chain multiple Elvis operators together to handle a series of nullable values. This is useful when you have...

middle

middle

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

junior

What is the difference between var and val in Kotlin?

senior

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

expert

What is the difference between * and Any in Kotlin generics?

Bình luận

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

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