Kotlin equivalent of ternary operator

johnny_crq

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?

Eric Cochran

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

ternary conditional operator equivalent?

From Java

Kotlin Ternary Conditional Operator

From Dev

Ternary Conditional Operator in kotlin

From Dev

SQL statement equivalent to ternary operator

From Dev

Can the ternary operator be equivalent to short circuiting with the logical operators?

From Java

What is the idiomatic Go equivalent of C's ternary operator?

From Dev

+ operator in a ternary operator

From Dev

Ruby ternary operator (or) or operator

From Dev

Ternary operator and increment operator

From Dev

Ternary Operator(Elvis Operator) ?:

From Dev

Ternary operator with "OR" operator not working?

From Java

Why does using the ternary operator to return a string generate considerably different code from returning in an equivalent if/else block?

From Dev

ternary construction not equivalent with if then else

From Dev

The &= Operator Equivalent

From Dev

Ternary operator with append (<<) operator and match

From Dev

Simple ternary operator not working

From Dev

Is it recommended to use Ternary operator?

From Dev

Ternary operator in aspx page

From Dev

Multiple parameters with ternary operator

From Dev

Using ternary operator in python?

From Dev

Ternary Operator in String

From Dev

Ternary operator left associativity

From Java

Ternary operator in AngularJS templates

From Dev

What is wrong with this ternary operator?

From Dev

Nullptr in ternary operator

From Dev

Ternary operator with multiple operations

From Dev

Extension to Hide Ternary Operator

From Dev

Throwing with the ternary operator

From Dev

ternary operator of different types