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

Where should I use var and where val ?

junior

What is basic difference between fold and reduce in Kotlin? When to use which?

junior

What is a primary constructor in Kotlin?

Bình luận

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

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