9

So in java we have the ternary operator (?), which sometimes is useful to easy some value computed by a if-else inlines. For example:

myAdapter.setAdapterItems( textToSearch.length == 0 ? noteList : noteList.sublist(0, length-5) ) 

I know the equivalent in kotlin would be:

myAdapter.setAdapterItems( if(textToSearch.length == 0) noteList else noteList.sublist(0, length-5) ) 

But i just used to love the ternary operator in Java, for short expression conditions, and when passing values to a method. Is there any Kotlin equivalent?

0

1 Answer 1

18

There is no ternary operator in Kotlin.

https://kotlinlang.org/docs/reference/control-flow.html

In Kotlin, if is an expression, i.e. it returns a value. Therefore there is no ternary operator (condition ? then : else), because ordinary if works fine in this role.

You can find a more detailed explanation here.

Sign up to request clarification or add additional context in comments.

6 Comments

Not a big fan of this, tbh
Maybe it is to avoid confusion with ?: and ? followed by : ... but I miss having it.
@JaysonMinard I feel like being able to use if in an infix form would take away much of the boilerplate.
@KirillRakhman @JaysonMinard Something like this isn't too unclear to me: (textToSearch.length == 0) +noteList -noteList.sublist(0, length-5) I implemented it like this: gist.github.com/Jire/46b1ee35855a5e97bfd5
The decision to use if...else as an expression probably goes along with the decision to use when (similar to switch) as an expression. But I think that replacing a ? b : c with if(a) b else c goes against the goal to make Kotlin more concise and readable then Java.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.