There is no ternary operator in Kotlin. It seems problematic at the first glance. But think we can do it with inline if else statement because this is expression here. Simply we have to do -
var number = if(n>0) "Positive" else "Negetive"
Here we can else if block too as many as we need. Like-
var number = if(n>0) "Positive" else if(n<0) "Negative" else "Zero"
So this line is so simple and much readable than ternary operator. when we use more than one ternary operator in java it seems horrible. But here we have a clear syntax. even we can write it in multiple line too.
With the following infix functions I can cover many common use cases pretty much the same way it can be done in Python :
class TestKotlinTernaryConditionalOperator {
@Test
fun testAndOrInfixFunctions() {
Assertions.assertThat(true and "yes" or "no").isEqualTo("yes")
Assertions.assertThat(false and "yes" or "no").isEqualTo("no")
Assertions.assertThat("A" and "yes" or "no").isEqualTo("yes")
Assertions.assertThat("" and "yes" or "no").isEqualTo("no")
Assertions.assertThat(1 and "yes" or "no").isEqualTo("yes")
Assertions.assertThat(0 and "yes" or "no").isEqualTo("no")
Assertions.assertThat(Date() and "yes" or "no").isEqualTo("yes")
@Suppress("CAST_NEVER_SUCCEEDS")
Assertions.assertThat(null as Date? and "yes" or "no").isEqualTo("no")
}
}
infix fun <E> Boolean?.and(other: E?): E? = if (this == true) other else null
infix fun <E> CharSequence?.and(other: E?): E? = if (!(this ?: "").isEmpty()) other else null
infix fun <E> Number?.and(other: E?): E? = if (this?.toInt() ?: 0 != 0) other else null
infix fun <E> Any?.and(other: E?): E? = if (this != null) other else null
infix fun <E> E?.or(other: E?): E? = this ?: other
There is no ternary operator in kotlin, as the
if else
block returns valueso, you can do:
val max = if (a > b) a else b
instead of java'smax = (a > b) ? b : c
We can also use
when
construction, it also return value:Here is link for kotlin documentation : Control Flow: if, when, for, while
There is no ternary operator in Kotlin. It seems problematic at the first glance. But think we can do it with inline if else statement because this is expression here. Simply we have to do -
Here we can else if block too as many as we need. Like-
So this line is so simple and much readable than ternary operator. when we use more than one ternary operator in java it seems horrible. But here we have a clear syntax. even we can write it in multiple line too.
Why would one use something like this:
when you can actually use something like this (
a
is boolean in this case):Java
Equivalent to Kotlin:
Another short approach to use
Here kotlin itself checks null value and if it is null then it passes empty string value.
With the following infix functions I can cover many common use cases pretty much the same way it can be done in Python :