Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary operator in kotlin [duplicate]

Tags:

android

kotlin

I can write in java

int i = 10;
String s = i==10 ? "Ten" : "Empty";

Even I can pass it in method parameter.

callSomeMethod(i==10 ? "Ten" : "Empty");

How do I convert it to kotlin? Lint shows error when writing same thing in kotlin.

like image 404
Khemraj Sharma Avatar asked Aug 10 '18 05:08

Khemraj Sharma


People also ask

Can we use ternary operator in Kotlin?

Briefly speaking, there is no ternary operator in Kotlin. However, using if and when expressions help to fill this gap.

Why there is no ternary operator in Kotlin?

In Kotlin, if is an expression: it returns a value. Therefore, there is no ternary operator ( condition ? then : else ) because ordinary if works fine in this role. If you're using if as an expression, for example, for returning its value or assigning it to a variable, the else branch is mandatory.

Can ternary operator replace if else statement?

The conditional operator – also known as the ternary operator – is an alternative form of the if/else statement that helps you to write conditional code blocks in a more concise way. First, you need to write a conditional expression that evaluates into either true or false .

What do you mean by ternary operator in Kotlin?

There is no ternary operator in kotlin, as the if else block returns the value. so, you can do: val max = if (a > b) a else b instead of java's max = (a > b) ? b : c. We can also use when construction, it also returns value: val max = when(a > b) { true -> a false -> b }


2 Answers

callSomeMethod( if (i==10) "Ten" else "Empty")

Discussion about ternary operator: https://discuss.kotlinlang.org/t/ternary-operator/2116/3

like image 126
Ilya E Avatar answered Sep 19 '22 21:09

Ilya E


Instead of

String s = i==10 ? "Ten" : "Empty";

Technically you can do

val s = if(i == 10) "Ten" else "Empty"

val s = when {
    i == 10 -> "Ten"
    else -> "Empty"
}

val s = i.takeIf { it == 10 }?.let { "Ten" } ?: "Empty"

// not really recommended, just writing code at this point
val s = choose("Ten", "Empty") { i == 10 } 
inline fun <T> choose(valueIfTrue: T, valueIfFalse: T, predicate: () -> Boolean) = 
    if(predicate()) valueIfTrue else valueIfFalse
like image 33
EpicPandaForce Avatar answered Sep 20 '22 21:09

EpicPandaForce