Conditional Expression

Using if/else as a replacement for the ternary operator in Kotlin

Gabriel Shanahan
The Kotlin Primer

--

— — — — — — — — — — — — — — —

THE CURRENT VERSION OF THIS ARTICLE IS PUBLISHED HERE.

— — — — — — — — — — — — — — —

Tags: #FYI

This article is part of the Kotlin Primer, an opinionated guide to the Kotlin language, which is indented to help facilitate Kotlin adoption inside Java-centric organizations. It was originally written as an organizational learning resource for Etnetera a.s. and I would like to express my sincere gratitude for their support.

It is recommended to read the Introduction before moving on. Check out the Table of Contents for all articles.

There is no ternary operator (i.e. <condition> ? <then> : <else>) in Kotlin. Instead, if/else may be used as an expression:

  1. if is an expression here — it returns a value. You can wrap each branch in { } if you need it to contain…

--

--