Sunday, October 29, 2017

Kotlin ternary operator and null handling

Android supports Java and Kotlin languages. So, recently found one interesting thing which have been using almost in every language.  That's the Ternary Operator.

But, to our surprise Kotlin does not support Ternary Operator. This is explained in control flow section of Kotlin documentation.

Instead of using ternary operator you will have to use the below expression

// As expression val max = if (a > b) a else b


Now there is something that was added to Kotlin language which could help us to , return  a default value in case null is encountered. In Swift we call it as Coalescing operator "??" and in Kotlin it is called Elvis operator "?:


Below is the code to print All Users.If you notice, I have used "?" next to Array<String>. "?" is for the compiler to know whether the parameter has nullable reference or not.

Also, args has a "?", Here the compile comes to know it is a safe call operator, so that it does not throw compile time error for null check.

fun printAllUsers(args: Array<String>?){
var userValue = args?.get(0)
var message = "User Name = ${userValue ?: "Name not available"}"
Log.d("print User =>",message)
}

Test: 
printAllUsers(arrayOf("John","Ted"))

printAllUsers(null)

Results
print User =>: User Name = John
print User =>: User Name = Name not available




So from the above code snippets we come to know two things, on is "No Ternary Operator in Kotlin" and "How to use default values in case object evaluates to null".