Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin equivalent of ternary operator [duplicate]

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?

like image 503
johnny_crq Avatar asked Jan 21 '16 22:01

johnny_crq


Video Answer


1 Answers

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.

like image 87
Eric Cochran Avatar answered Sep 19 '22 18:09

Eric Cochran