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

后端 未结 8 871
青春惊慌失措
青春惊慌失措 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条回答
  •  旧时难觅i
    2020-11-29 01:20

    This is called the Elvis operator and it does... Exactly what you've described in your question. If its left hand side is a null value, it returns the right side instead, sort of as a fallback. Otherwise it just returns the value on the left hand side.

    a ?: b is just shorthand for if (a != null) a else b.

    Some more examples with types:

    val x: String? = "foo"
    val y: String = x ?: "bar"      // "foo", because x was non-null    
    
    val a: String? = null
    val b: String = a ?: "bar"      // "bar", because a was null
    

提交回复
热议问题