Elvis Operator And Range Traversal Of An Array Kotlin

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.
  1. public static boolean exists(String source, char element) {  
  2.    if (source != null) {  
  3.       return source.indexOf(element) != -1;  
  4.       }  
  5.    return false;  
  6. }  
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:
  1. fun elvisSample(arg : String?) {  
  2.    val value = arg ?: ""  
  3. }  
Let's take another example :
  1. var str: String? = null  
  2. 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:
  1. fun main(args: Array<String>){  
  2.    var str: String? = null  
  3.    var str2: String? = "May be declare nullable string"  
  4.    var len1: Int = if (str != null) str.length else -1  
  5.    var len2: Int = if (str2 != null) str2.length else -1  
  6.    println("Length of str is ${len1}")  
  7.    println("Length of str2 is ${len2}")  
  8. }  
Output
 
Length of str is -1
Length of str2 is 30
 
Access using Elvis operator
  1. fun main(args: Array<String>){  
  2.    var str: String? = null  
  3.    var str2: String? = "May be declare nullable string"  
  4.    var len1: Int = str ?.length ?: -1  
  5.    var len2: Int = str2 ?.length ?: -1  
  6.    println("Length of str is ${len1}")  
  7.    println("Length of str2 is ${len2})  
  8. }  
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:
  1. fun main(args: Array<String>){  
  2.    val fruitName: String = fruits()  
  3.    println(fruitName)  
  4. }  
  5. fun fruits(): String{  
  6.    val str: String? ="abc"  
  7.    val strLength: Int = if(str!= null) str.length else -1  
  8.    val strLength2: Int = str?.length ?: -1  
  9.    var string = "str = $str\n"+  
  10.    "strLength = $strLength\n"+  
  11.    "strLength2 = $strLength2\n\n"  
  12.    fun check(textOne: String?, textTwo: String?): String?{  
  13.       val textOne = textOne ?: return null  
  14.       val textTwo = textTwo ?: IllegalArgumentException("text exception")  
  15.       return "\ntextOne = $textOne\n"+  
  16.       "textTwo = $textTwo\n"  
  17.       }  
  18.    string += "check(null,\"mango\") = ${check(null,"mango")}\n" +  
  19.    "check(\"apple\",\"orange\") = ${check("apple","orange")}\n"  
  20.    return string  
  21. }  
Output
 
str = abc
strLength = 3
strLength2 = 3
check(null,"mango") = null
check("apple","orange") =
textOne = apple
textTwo = orange
 
Now let's talk about the array declaration in Kotlin using traditional and modern methods as well.
  1. var myArray = Array<Int>(5){0}  
This array initializes all five elements to zero. Now the other type of declaration is as follows : 

Kotlin array declaration - using arrayOf function
  1. var myArray1 = arrayOf(1,10,4,6,15)    
  2. var myArray2 = arrayOf<Int>(1,10,4,6,15)    
  3. val myArray3 = arrayOf<String>("Ajay","Prakesh","Michel","John","Sumit")    
  4. var myArray4= arrayOf(1,10,4"Ajay","Prakesh")    
Let's code some lines to show how this arrayOf function works.
  1. fun main(args: Array<String>){    
  2.     val name = arrayOf<String>("Ajay","Prakesh","Michel","John","Sumit")    
  3.     var myArray2 = arrayOf<Int>(1,10,4,6,15)    
  4.     var myArray3 = arrayOf(5,10,20,12,15)    
  5.     var myArray4= arrayOf(1,10,4"Ajay","Prakesh")    
  6.     var myArray5: IntArray = intArrayOf(5,10,20,12,15)    
  7.     
  8.     for(element in name){    
  9.         println(element)    
  10.     }    
  11.     
  12.     println()    
  13.     for(element in myArray2){    
  14.         println(element)    
  15.     }    
  16.     println()    
  17.     for(element in myArray3){    
  18.         println(element)    
  19.     }    
  20.     println()    
  21.     for(element in myArray4){    
  22.         println(element)    
  23.     }    
  24.     println()    
  25.     for(element in myArray5){    
  26.         println(element)    
  27.     }    
  28.     
  29. }    
Output
 
Ajay
Prakesh
Michel
John
Sumit
1
10
4
6
15
5
10
20
12
15
1
10
4
Ajay
Prakesh
5
10
15
20
25
 
Example 2
 

Kotlin Array - traversing using range.


The Kotlin's array elements also traverse using index range (minValue..maxValue) or (maxValue..minvalue). Let's see an example of array traversing using range.
  1. fun main(args: Array<String>){    
  2.     var myArray5: IntArray = intArrayOf(5,10,20,12,15)    
  3.     
  4.     for (index in 0..4){    
  5.         println(myArray5[index])    
  6.     }    
  7.     println()    
  8.     for (index in 0..myArray5.size-1){    
  9.         println(myArray5[index])    
  10.     }    
  11. }    
Output
 
5
10
20
12
15
5
10
20
12
15


Similar Articles