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

后端 未结 8 833
青春惊慌失措
青春惊慌失措 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

    The elvis operator in Kotlin is used for null safety.

    x = a ?: b
    

    In the above code, x will be assigned the value of a if a is not null and b if a is null.

    The equivalent kotlin code without using the elvis operator is below:

    x = if(a == null) b else a
    
    0 讨论(0)
  • 2020-11-29 01:34

    A little addition though is this

    X = A ?: B
    

    X will still be null if both A and B evaluate to null

    Therefore, if you want X to always be non-null, make sure B is always a non-null or that B always evaluates to non-null if it's a function or expression.

    0 讨论(0)
提交回复
热议问题