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

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

    TL;DR: If the resulting object reference [first operand] is not null, it is returned. Otherwise the value of the second operand (which may be null) is returned


    The Elvis operator is part of many programming languages, e.g. Kotlin but also Groovy or C#. I find the Wikipedia definition pretty accurate:

    In certain computer programming languages, the Elvis operator ?: is a binary operator that returns its first operand if that operand is true, and otherwise evaluates and returns its second operand. It is a variant of the ternary conditional operator, ? :, found in those languages (and many others): the Elvis operator is the ternary operator with its second operand omitted.

    The following is especially true for Kotlin:

    Some computer programming languages have different semantics for this operator. Instead of the first operand having to result in a boolean, it must result in an object reference. If the resulting object reference is not null, it is returned. Otherwise the value of the second operand (which may be null) is returned.

    An example:

    x ?: y // yields `x` if `x` is not null, `y` otherwise.
    

提交回复
热议问题