Friday, 2 February 2018

Kotlin Ternary Conditional Operator



What is the equivalent of this expression in Kotlin?




a ? b : c


This is not valid code in Kotlin.


Answer



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.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...