Robert MacLean
3 July 2018
**More Information**
- This is the 12th post in a multipart series.
If you want to read more, see our series index
We are going to take a short break from the Koans and look at a cool trick I learnt today. Previously, we learnt about the safe null operator but that only helps when calling functions or properties of objects…
fun ifDemo1(name:String?) {
val displayName = if (name != null) name else "Mysterious Stranger"
println("HI ${displayName}")
}
In the above example, we have the name
String which could be null but safe null operator (this needs a better name) can’t help here… so let us look at what Kotlin calls the Elvis operator ?:
and what it gives us:
fun ifDemo2(name:String?) {
val displayName = name ?: "Mysterious Stranger"
println("YO ${displayName}")
}
This is really cool and reminds me of SQL COALESCE where it lets you test the first value and if it is not null, it returns the first value, else it returns the second value.