What does the ?: operator do in Kotlin? (Elvis Operator)
Hi everyone! I recently started learning Kotlin and came across a strange operator `?:`. I saw it in someone else's code but can't understand what it does.
For example, there is this code:
```kotlin
val name: String? = null
val result = name ?: "Unknown"
```
I understand that `String?` means the variable can be null. But what does `?:` do? Why does `result` become "Unknown" even though `name` is null? In Java, I would write `if (name != null) name else "Unknown"`, but here it's just one symbol.
Please explain in simple terms how this operator works and show examples. I'm also curious if it can be used not only with simple values but also with functions? And are there any pitfalls?
Thanks in advance!
No answers yet.
Log in to leave an answer
Blogs