Programming
kotlin conditional-operator
Updated Sat, 25 Jun 2022 02:23:41 GMT

How to write ternary conditional operator?


What is the equivalent of this expression in Kotlin?

a ? b : c

This is not valid code in Kotlin.




Solution

In Kotlin, if statements are expressions. So the following code is equivalent:

if (a) b else c

The distinction between expression and statement is important here. In Java/C#/JavaScript, if forms a statement, meaning that it does not resolve to a value. More concretely, you can't assign it to a variable.

// Valid Kotlin, but invalid Java/C#/JavaScript
var v = if (a) b else c

If you're coming from a language where if is a statement, this might seem unnatural but that feeling should soon subside.





Comments (5)

  • +0 – Additionally you can use when. — May 02, 2013 at 14:59  
  • +0 – just to add, if it's a boolean expression, you can even go with x = a==b — May 08, 2017 at 16:29  
  • +0 – Special mention for var v = a ?: b. This is same as var v = if(a != null) a else b — Jan 10, 2018 at 04:16  
  • +6 – @AdeelAnsari No, it is not rectifying. It is worse. Compare this. b + if (a) c else d vs. b + (c if (a) else d) The latter one requires additional parentheses. because c is not enclosed by the condition and else. — Mar 12, 2018 at 04:46  
  • +4 – Here is a little discussion about this topic. discuss.kotlinlang.org/t/ternary-operator/2116/141 — Apr 18, 2018 at 05:55