Elvis Operator (?:) in Kotlin
On this page (6sections)
Definition
- This operator is used for null safety in Kotlin.
- It is mainly used for operations involving boxed values (Values which may hold “null”).
- It is represented by ”?:”
- If the value to the left of Elvis Operator is null, the value on the right side of the operator is returned as the result.
- If the value to the left sidde of Elvis Operator is not null then the same value is returned as the result.
Syntax
/*If the value at the variable "string" is null, "100" is assigned to the variable "length" and if it is not null, the value of the length of the string is assigned to the variable "length".*/
value length = string?.length ?: 100
Elvis Operator (?:) Example Program in Kotlin
//Elvis Operator Example Program in Kotlin
//Operator Kotlin Programs, Basic Kotlin Program
fun main(args: Array<String>) {
//Declaring a boxed string and assigning a non-null value
var name: String? = "Little Drops"
var result = getLength(name)
println("Length of $name is $result")
//Assigning null to the name variable
name = null
result = getLength(name)
println("Length of $name is $result")
}
//Function to find the length of a boxed string which returns 0 when the string is null.
fun getLength(name : String?) : Int?{
return name?.length ?: 0
}
Sample Output
Length of Little Drops is 12
Length of null is 0
How It Works
This Kotlin program demonstrates Elvis Operator (?:). It first prepares the data it needs, then uses conditional logic to decide the result, and finally prints the output shown in the Sample Output above.
- Declare the variables that hold the program’s data.
- Use conditional statements to handle the different cases.
- Print the final result to the console so you can compare it with the sample output.
Try changing the input values and re-running the program to see how the output changes — this is the fastest way to understand how the logic behaves.
Frequently Asked Questions
What is Elvis Operator (?:) in Kotlin?
This operator is used for null safety in Kotlin.
How do I run this Kotlin example?
Run it in IntelliJ IDEA or Android Studio, or compile from the command line with `kotlinc file.kt -include-runtime -d file.jar` and run `java -jar file.jar`.
How can I practice Elvis Operator (?:)?
Copy the example into IntelliJ IDEA or Android Studio, run it, then change the values or add print statements to see how the output changes.