Kotlin Ternary: The follow-up

Please don't use this...

February 18, 2024


Foreword

This article is a sequel to this article:

After posting that article I realized a better way to make a ternary function in Kotlin… and it’s rather cursed.

Hurry up

Alright. Well. This is absolutely horrible. Never use this, please.

Cursed Ternary
infix fun <T : Any> Boolean.`?`(v: T) = this to v
infix fun <T : Any> Pair<Boolean, T>.`:`(v: T) =
    if (first) second else v

// this works because it's eval'd LTR
// so "false ? true" becomes a pair and
// ": false" evaluates the ternary
val a = false `?` "true" `:` "false"

This can’t be that bad… right?

It is that bad

Yeah, the thing that stands out as being the worst part is that no matter what, the true branch will be evaluated meaning you can’t use any thing that creates a side effect as values for the branches of the ternary. You can of course adapt the function to take in () -> T parameters, but I’ll leave that as an exercise to the reader :^)