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

I can’t understand what is doing ?:, for example, in this case

val list = mutableList ?: mutableListOf() 

and why it can be changed to this

val list = if (mutableList != null) mutableList else mutableListOf()
+43
source share
6 answers

TL DR: if the resulting object reference [first operand] is not equal 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, for example, Kotlin, as well as Groovy or C #. I find the definition of Wikipedia fairly accurate:

?: , , true, . ? : ? :, ( ): - , .

Kotlin:

. , , . null, . ( null).

:

x ?: y // yields 'x' if 'x' is not null, 'y' otherwise.
+57

, : ?: :

first operand ?: second operand

:

first operand , . , second operand. , , , .


( ):

fun retrieveString(): String {    //Notice that this type isn't nullable
    var nullableVariable: String? = getPotentialNull() //This variable may be null

    return nullableVariable ?: "Secondary Not-Null String"
}

, getPotentialNull , retrieveString; , "Secondary Not-Null String".

, , .

Kotlin second operand, , throw Exception

return nullVariable ?: throw IllegalResponseException("My inner function returned null! Oh no!")

Elvis Operator .

Elvis QuestionMark

: , . , . Android Kotlin. 2017. Packt Publishing

+43

Elvis operator, ... , . null, , . .

a ?: b if (a != null) a else b.

:

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
+32

:

r, " r , , x":

?: (Elvis) .

, null .

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

?: , . , , :

val l = listOf(1, 2, 3)

val x = l.firstOrNull { it == 4 } ?: l.firstOrNull { it == 5 } ?: throw IllegalStateException("Ups")

if else, , .

+8

, . , ? , return empty busy

Java:

private int a;
if(a != null){
    println("a is not null, Value is: "+a)
}
else{
    println("a is null")
}

:

val a : Int = 5
val l : Int = if (a != null) a.length else "a is null"
0

, - , .

..

val number: Int? = null
println(number ?: "Number is null")

Thus, if the number is NOT equal to zero , a number will be printed, otherwise, "Number is zero" will be printed.

0
source

Source: https://habr.com/ru/post/1692168/


All Articles