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

It’s similar but better

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 {…

--

--