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.
Briefly speaking, there is no ternary operator in Kotlin. However, using if and when expressions help to fill this gap.
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.
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 .
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 }
callSomeMethod( if (i==10) "Ten" else "Empty")
Discussion about ternary operator: https://discuss.kotlinlang.org/t/ternary-operator/2116/3
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With