Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

FlexNet Code Aware, a free scan tool for developers. Scan Java, NuGet, and NPM packages for open source security and open source license compliance issues.

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.

 Scan Java, NuGet, and NPM packages for open source security and license compliance issues. 

Topics:
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 }}