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
- }
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.
- 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
- var myArray1 = arrayOf(1,10,4,6,15)
- var myArray2 = arrayOf<Int>(1,10,4,6,15)
- val myArray3 = arrayOf<String>("Ajay","Prakesh","Michel","John","Sumit")
- var myArray4= arrayOf(1,10,4, "Ajay","Prakesh")
Let's code some lines to show how this arrayOf function works.
- fun main(args: Array<String>){
- val name = arrayOf<String>("Ajay","Prakesh","Michel","John","Sumit")
- var myArray2 = arrayOf<Int>(1,10,4,6,15)
- var myArray3 = arrayOf(5,10,20,12,15)
- var myArray4= arrayOf(1,10,4, "Ajay","Prakesh")
- var myArray5: IntArray = intArrayOf(5,10,20,12,15)
-
- for(element in name){
- println(element)
- }
-
- println()
- for(element in myArray2){
- println(element)
- }
- println()
- for(element in myArray3){
- println(element)
- }
- println()
- for(element in myArray4){
- println(element)
- }
- println()
- for(element in myArray5){
- println(element)
- }
-
- }
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.
- fun main(args: Array<String>){
- var myArray5: IntArray = intArrayOf(5,10,20,12,15)
-
- for (index in 0..4){
- println(myArray5[index])
- }
- println()
- for (index in 0..myArray5.size-1){
- println(myArray5[index])
- }
- }
Output
5
10
20
12
15
5
10
20
12
15