Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 493 Vote(s) - 3.55 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Kotlin Ternary Conditional Operator

#1
What is the equivalent of this expression in Kotlin?

a ? b : c

This is not valid code in Kotlin.
Reply

#2
For myself I use following extension functions:

fun T?.or<T>(default: T): T = if (this == null) default else this
fun T?.or<T>(compute: () -> T): T = if (this == null) compute() else this

First one will return provided default value in case object equals null. Second will evaluate expression provided in lambda in the same case.

Usage:

1) e?.getMessage().or("unknown")
2) obj?.lastMessage?.timestamp.or { Date() }

Personally for me code above more readable than ```if``` construction inlining
Reply

#3
when replaces the switch operator of C-like languages. In the simplest form it looks like this

when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> {
print("x is neither 1 nor 2")
}
}
Reply

#4
> 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. [manual source from here][1]

// Traditional usage
var max = a
if (a < b) max = b

// With else
var max: Int
if (a > b) {
max = a
} else {
max = b
}

// As expression
val max = if (a > b) a else b


[1]:

[To see links please register here]

Reply

#5
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.
Reply

#6
Another short approach to use

val value : String = "Kotlin"

value ?: ""

Here kotlin itself checks null value and if it is null then it passes empty string value.
Reply

#7
You could define your own `Boolean` extension function that returns `null` when the `Boolean` is `false` to provide a structure similar to the ternary operator:

infix fun <T> Boolean.then(param: T): T? = if (this) param else null

This would make an `a ? b : c` expression translate to `a then b ?: c`, like so:

println(condition then "yes" ?: "no")

**Update:**
But to do some more Java-like conditional switch you will need something like that

```infix fun <T> Boolean.then(param: () -> T): T? = if (this) param() else null```

```println(condition then { "yes" } ?: "no")```
pay attention on the lambda. its content calculation should be postponed until we make sure `condition` is `true`

This one looks clumsy, [that is why there is high demanded request exist to port Java ternary operator into Kotlin](

[To see links please register here]

)
Reply

#8
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
Reply

#9
Java

int temp = a ? b : c;

Equivalent to Kotlin:

var temp = if (a) b else c
Reply

#10
You can do it many way in Kotlin

1. Using if


if(a) b else c



2. Using when

when (a) {
true -> print("value b")
false -> print("value c")
else -> {
print("default return in any other case")
}
}




3. Null Safety


val a = b ?: c


Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through