Kotlin Ternary Conditional Operator

2019-01-06 10:01发布

What is the equivalent of this expression in Kotlin?

a ? b : c

This is not valid code in Kotlin.

27条回答
来,给爷笑一个
2楼-- · 2019-01-06 10:24

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")
    }
}
查看更多
等我变得足够好
3楼-- · 2019-01-06 10:25

example: var energy: Int = data?.get(position)?.energy?.toInt() ?: 0

In kotlin if you are using ?: it will work like if the statement will return null then ?: 0 it will take 0 or whatever you have write this side.

查看更多
男人必须洒脱
4楼-- · 2019-01-06 10:26

TL;DR

if (a) b else c is what you can use instead of the Java expression a ? b : c.


In Kotlin, many control statements including if, when or even try can be used as expressions. This means that those can have a result which can be assigned to a variable, returned from a function etc.

Syntactically, no need for ternary operator

As a result, Kotlin does not need the ternary operator.

if (a) b else c is what you can use instead of the Java expression a ? b : c.

I think the idea is that the latter is less readable since everybody knows what ifelse does, whereas ? : is rather inconvenient if you're not familar with the syntax already. Although I have to admit that I often miss the more convenient ternary operator.


Other Alternatives

when

You might also see a lot when constructs whenever conditions are checked in Kotlin. It's also a way to express if-else cascades in an alternative way. The following corresponds to your example.

when(a) {
    true -> b
    false -> c
}

Extensions

As many good examples (Kotlin Ternary Conditional Operator) in the other answers show, extensions can also be a way to go.

查看更多
欢心
5楼-- · 2019-01-06 10:27

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

// 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
查看更多
看我几分像从前
6楼-- · 2019-01-06 10:27

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
    
查看更多
祖国的老花朵
7楼-- · 2019-01-06 10:28

There is no ternary operation in Kotlin, but there are some fun ways to work around that. As others have pointed out, a direct translation into Kotlin would look like this:

val x = if (condition) result1 else result2

But, personally, I think that can get a bit cluttered and hard to read. There are some other options built into the library. You can use takeIf {} with an elvis operator:

val x = result1.takeIf { condition } ?: result2

What is happening there is that the takeIf { } command returns either your result1 or null, and the elvis operator handles the null option. There are some additional options, takeUnless { }, for example:

val x = result1.takeUnless { condition } ?: result2

The language is clear, you know what that's doing.

If it's a commonly used condition, you could also do something fun like use an inline extension method. Let's assume we want to track a game score as an Int, for example, and we want to always return 0 if a given condition is not met:

inline fun Int.zeroIfFalse(func: () -> Boolean) : Int = if (!func.invoke()) 0 else this     

Ok, that seems ugly. But consider how it looks when it is used:

var score = 0
val twoPointer = 2
val threePointer = 3

score += twoPointer.zeroIfFalse { scoreCondition } 
score += threePointer.zeroIfFalse { scoreCondition } 

As you can see, Kotlin offers a lot of flexibility in how you choose to express your code. There are countless variations of my examples and probably ways I haven't even discovered yet. I hope this helps!

查看更多
登录 后发表回答