What does ?: do in Kotlin? (Elvis Operator)

后端 未结 8 859
青春惊慌失措
青春惊慌失措 2020-11-29 01:15

I can\'t figure out what ?: does in for example this case

val list = mutableList ?: mutableListOf() 

and why can it be modifi

8条回答
  •  渐次进展
    2020-11-29 01:34

    Let's take a look at the defintion:

    When we have a nullable reference r, we can say "if r is not null, use it, otherwise use some non-null value x":

    The ?: (Elvis) operator avoids verbosity and makes your code really concise.

    For example, a lot of collection extension functions return null as fallback.

    listOf(1, 2, 3).firstOrNull { it == 4 } ?: throw IllegalStateException("Ups")
    

    ?: gives you a way to handle the fallback case elgantely even if you have multiple layers of fallback. If so, you can simply chain multiply Elvis operators, like here:

    val l = listOf(1, 2, 3)
    
    val x = l.firstOrNull { it == 4 } ?: l.firstOrNull { it == 5 } ?: throw IllegalStateException("Ups")
    

    If you would express the same with if else it would be a lot more code which is harder to read.

提交回复
热议问题