Kotlin Elvis Operator: A Strong Null Safety Helper (Example)
In this Kotlin tutorial, we will explore the use case of the Kotlin Elvis operator—a concise and powerful feature that streamlines null checking in your code. First of all, let’s grasp the essence of the Elvis operator itself. In Kotlin, the Elvis operator, denoted by `?:`, primarily handles null safety.
For example, consider the following example:
fun main() {
val userInput = null
val result = if(userInput != null) userInput else "Nothing"
println(result)
}
In this scenario, if `userInput` is not null, it will be assigned to ‘result‘; otherwise, ‘Nothing‘ (default value) will be used.
Output will be:
Nothing
Here the operator is not explicitly used. The Elvis operator is an alternative syntax for expressing the same logic more precisely. The equivalent code using the Elvis operator is given below:
Let’s use Kotlin Elvis Operator (?:)
Let’s rewrite the above code using the Elvis operator. Open the Kotlin Playground on your computer and write the following code.
fun main() {
val userInput: String? = null
val result = userInput ?: "Nothing"
println(userInput)
println(result)
}
Output
null
Nothing
It is a concise way to handle nullable expressions by providing a default value if the expression on the left side is null. If ‘userInput‘ is not null, it will be assigned to ‘result‘; otherwise, ‘Nothing’ (a default value) will be used. The Elvis operator is a useful tool for handling nullability in a readable manner in Kotlin.
However, it’s important to note that the Elvis is not a silver bullet for all null-related challenges. It primarily addresses the case of providing a default value when encountering a null reference.
In this tutorial, we’ve explored how the Elvis operator can handle null-checks, making code more concise and readable. It’s a handy tool in scenarios where you need to assign a default value if a nullable variable is null.
For example, let’s consider a situation where you’re retrieving data from a database, and some fields might be null.
Example
fun main() {
var check = User.name ?: "Guest"
println(check)
var check2 = User.id ?: 0
println(check2)
}
class User{
companion object{
var name: String? = null
var id: Int? = 3454
}
}
Guest
3454
Kotlin provides a diverse set of operators to handle a wide range of operations efficiently. Arithmetic operators perform basic mathematical calculations, while comparison operators facilitate value comparisons. Logical operators, such as && and ||, support boolean logic. Assignment operators streamline variable assignments, and increment/decrement operators simplify value modifications.
Happy Coding!