VOOZH about

URL: https://www.geeksforgeeks.org/kotlin/kotlin-elvis-operator/

⇱ Kotlin Elvis Operator(?:) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Kotlin Elvis Operator(?:)

Last Updated : 15 Jun, 2025

In Kotlin, the Elvis Operator (?:) is a very useful tool when working with nullable variables. It helps us to provide a default value if an expression returns null. This operator makes our code shorter, cleaner, and safer when dealing with possible null values.

Definition:

Sometimes in Kotlin, we declare variables that can hold null references. Before using such variables, we usually check if they are null or not to avoid errors like NullPointerException. Instead of using long if-else conditions, we can use the Elvis Operator (?:) to make the code much simpler.

Syntax:

val result = expression ?: default_value

If expression is not null, it returns the value of the expression. If expression is null, it returns the default_value after ?:.

To normally handle null values using an if-else block we do it the following way as shown below.

Example:

Output:

Length of st is -1
Length of st1 is 15

Example:

In this example, for "st", since it is null, we return -1 and for "st1", since it is not null, we return its length (15).


We can do the same thing more easily using the Elvis Operator (?:) as shown below.

Example:

Output:

Length of st is -1
Length of st1 is 15

Explanation:

  • st?.length tries to get the length of "st".
  • But since "st" is null, the Elvis Operator (?:) gives the value -1.
  • For "st1", which is not null, we get the actual length.
Comment
Article Tags:
Article Tags:

Explore