Introduction
Kotlin is a new generation language and very null safe. According to docs "The Elvis operator in Kotlin is an operator that receives two inputs and returns the first argument if it is non-null or the second one otherwise. It is fancily called the null-coalescing operator. It is a variant of the ternary operator but for null-safety checking.".
Motivation
As you know, Java is a programming language where we frequently encounter the NullPointerExceptions. Kotlin creators kept that in mind and developed a null safe language. If you are writing pure Kotlin code, then chances are you may not deal with nullable types. But the Java JDK, Android framework and other Java libraries will force you to deal with them. Let us look at how verbose it is to check for nullability in Java.
Lets have a look to java code that simply shows the null check as to keep code null safe.
- public static boolean exists(String source, char element) {
- if (source != null) {
- return source.indexOf(element) != -1;
- }
- return false;
- }
In Java we have to write the additional minimum three lines to make code safe as shown above. To overcome this, Kotlin introduce the Elvis operator.
How to use the Elvis operator?
The syntax of the Elvis operator is ?:. A simple example would be:
- fun elvisSample(arg : String?) {
- val value = arg ?: ""
- }
Let's take another example :
- var str: String? = null
- var str2: String? = "May be declare nullable string"
Here str contains null value and str2 contains non null value.
Access using traditional if else method:
- fun main(args: Array<String>){
- var str: String? = null
- var str2: String? = "May be declare nullable string"
- var len1: Int = if (str != null) str.length else -1
- var len2: Int = if (str2 != null) str2.length else -1
- println("Length of str is ${len1}")
- println("Length of str2 is ${len2}")
- }
Output
Length of str is -1
Length of str2 is 30
Access using Elvis operator
- fun main(args: Array<String>){
- var str: String? = null
- var str2: String? = "May be declare nullable string"
- var len1: Int = str ?.length ?: -1
- var len2: Int = str2 ?.length ?: -1
- println("Length of str is ${len1}")
- println("Length of str2 is ${len2})
- }
Output
Length of str is -1
Length of str2 is 30
Kotlin Elvis Operator using throw and return expression
As Kotlin throws and returns an expression, they can also be used on the right side of the Elvis operator. This can be used for checking functional arguments:
- fun main(args: Array<String>){
- val fruitName: String = fruits()
- println(fruitName)
- }
- fun fruits(): String{
- val str: String? ="abc"
- val strLength: Int = if(str!= null) str.length else -1
- val strLength2: Int = str?.length ?: -1
- var string = "str = $str\n"+
- "strLength = $strLength\n"+
- "strLength2 = $strLength2\n\n"
- fun check(textOne: String?, textTwo: String?): String?{
- val textOne = textOne ?: return null
- val textTwo = textTwo ?: IllegalArgumentException("text exception")
- return "\ntextOne = $textOne\n"+
- "textTwo = $textTwo\n"
- }
- string += "check(null,\"mango\") = ${check(null,"mango")}\n" +
- "check(\"apple\",\"orange\") = ${check("apple","orange")}\n"
- return string
- }

Join the conversation! Your thoughts help the community grow.