When would you use Elvis operator in Kotlin?
When would you use Elvis operator in Kotlin?
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:
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:
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"
.
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:
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.
You can chain multiple Elvis operators together to handle a series of nullable values. This is useful when you have...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào