Over a million developers have joined DZone.

Learning Kotlin: Kotlin's Elvis Operator [Snippet]

DZone 's Guide to

Learning Kotlin: Kotlin's Elvis Operator [Snippet]

Check out this code snippet on using Kotlin's Elvis Operator as an alternative to the safe null operator.

· Java Zone ·
Free Resource

Today, we are going to take a short break from the Koans and look at a cool trick that I learned. Previously, we learned 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 that could be null. However, the safe null operator can't help here. So, let's look at Kotlin's Elvis operator ?: and what it can do for us:

fun ifDemo2(name:String?) {
    val displayName = name ?: "Mysterious Stranger"
    println("YO ${displayName}")

This is really cool and reminds me of SQL COALESCE, because it lets you test the first value. If it is not null, it returns the first value, else it returns the second value.

java ,tutorial ,kotlin ,elvis operator ,safe null operator ,operators

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}