Ternary operator in kotlin [duplicate]

2019-07-10 05:08发布

问题:

This question already has an answer here:

  • Kotlin Ternary Conditional Operator 28 answers

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.

回答1:

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

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



回答2:

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


回答3:

You can create an extension function with generic for boolean value

 fun <T> Boolean.elvis( a :T, b :T ): T{
     if(this) // this here refers to the boolean result
         return a
     else
         return b
}

and now you can use it for any boolean value (cool Kotlin)

//                                         output
System.out.print((9>6).elvis("foo","bar")) foo
System.out.print((5>6).elvis("foo","bar")) bar

Extensions in kotlin



回答4:

As the original question was using the term 'Elvis operator' it may be a good idea to provide a short comparison with the ternary operator.

The main difference between ternary operator and Elvis operator is that ternary is used for a short if/else replacement while the Elvis operator is used for null safety, e.g.:

  • port = (config.port != null) ? config.port : 80; - a shortcut for an if/then/else statement
  • port = config.port ?: 80 - provides a default value to be used in case the original one is null

The examples look very similar but the Ternary operator can be used with any type of boolean check while the Elvis operator is a shorthand for use config.port if it's not null else use 80 so it only checks for null.

Now, I think Kotlin doesn't have a ternary operator and you should use an if statement like so - s = if (i==10) "Ten" else "Empty"