Learning Kotlin: Kotlin's Elvis Operator

Submitted by Robert MacLean on Tue, 07/03/2018 - 09:00
**More Information** * This is the 12th post in a multipart series. If you want to read more, see our [series index](/learning-kotlin-introduction) 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](/learning-kotlin-nullable-types) 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](https://docs.microsoft.com/en-us/sql/t-sql/language-elements/coalesce-transact-sql?view=sql-server-2017) 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.