I can\'t figure out what ?:
does in for example this case
val list = mutableList ?: mutableListOf()
and why can it be modifi
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.