Why Kotlin’s Elvis Operator is Better Than Swift’s Guard Statement

It’s similar but better

Elye
Elye
May 4, 2020 · 3 min read
Image for post
Image for post
Picture by Mediamodifier on Pixabay

If you’ve programmed for iOS Swift before, you’ll find this interesting keyword, guard, that helps to guard and ensure some condition is met or some variable is not null before proceeding.

func process(couldBeNullMesage: String?) {
guard let notNullMessage = couldBeNullMesage else { return }
printMessage(notNullMessage)
// ... and a lot more
// things to do...
}
func printMessage(message: String) {
print(message)
}

Something like the above is common, where guard is used to prevent any subsequent code from being executed if a null value is received.

Coming from the Android and Kotlin world, I find guard fascinating. I gave a quick think about what the equivalent in Kotlin might be.

Four Different Ways in Kotlin (Getting Better Each Time)

If you’re short on patience, you can go straight to the fourth approach — which amazes me.

The popular let approach

Everybody who first learns Kotlin loves let.

fun process(couldBeNullMesage: String?) {
couldBeNullMesage?.let {
printMessage(it)
// ... and a lot more
// things to do...
}
}
fun printMessage(message: String) {
println(message)
}

This definitely does the work. However, all the code in the function will need to have an extra indentation.

As mentioned in this article, let isn’t always a good option.

2. The Elvis-operator approach

In Kotlin, the Elvis operator is similar to Swift coalescing — but a little smarter. It can assign a non-null value to another variable, and if it is null, it can execute return.

fun process(couldBeNullMesage: String?) {    val notNullMessage = couldBeNullMesage ?: return    printMessage(notNullMessage) // this is autocast to non-null.
// ... and a lot more
// things to do...
}
fun printMessage(message: String) {
println(message)
}

This is almost like the guard equivalent in the Swift language. It’s already better than guard, as it doesn’t need a parenthesis to wrap the return.

In Swift, we can’t do the following, as it expects a valid string on the right side of coalescing — i.e., ??.

val notNullMessage = couldBeNullMesage ?? return

Nonetheless, I’m still not content with the Elvis-operator approach above. The conventional approach below looks even better.

3. Conventional if-else approach

Let’s use what the Java convention teaches us: the old, faithful if-else.

fun process(couldBeNullMesage: String?) {    if (couldBeNullMesage == null) return    printMessage(couldBeNullMesage) // smartcast to non-null.
// ... and a lot more
// things to do...
}
fun printMessage(message: String) {
println(message)
}

In Kotlin, the smart casting of a null-checked variable to a non-nullvariable eliminates the need for a temporary variable.

But wait! There’s an even better way.

4. The smart cast–Elvis operator approach

What if we combine the Elvis operator and the smart-cast capability of Kotlin together — how would it look like?

fun process(couldBeNullMesage: String?) {    couldBeNullMesage ?: return    printMessage(couldBeNullMesage) // smartcast to non-null.
// ... and a lot more
// things to do...
}
fun printMessage(message: String) {
println(message)
}

Hallelujah! This is just genius. Concise and to the point.

A Quick Comparison

// Swift 
guard
let notNullMessage = couldBeNullMesage else { return }
// Kotlin
couldBeNullMesage ?: return

Sorry if I started a battle between iOS and Android. Some credit should go to iOS, as states below:

  • I have to thank iOS Swift for letting me ponder this by learning about guard
  • To be fair, guard isn’t just for the sole purpose of checking the null value. It’s used in other contexts (e.g., boolean variables, check for more variabless), which can’t be done with a single Kotlin Elvis operation.

It’s just in this context purely that, in my opinion, Kotlin does better.

Thanks for reading.

Mobile App Development Publication

Sharing Mobile App Development and Learning

Elye

Written by

Elye

Passionate about learning, and sharing mobile development and others https://twitter.com/elye_project https://www.facebook.com/elye.proj

Mobile App Development Publication

Sharing iOS, Android and relevant Mobile App Development Technology and Learning

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store