What does the ?: operator do in Kotlin? (Elvis operator)
Hi! I just started learning Kotlin after Java and came across a strange ?: operator. I saw it in someone else's code but can't understand what it does.
Here's an example I found:
```kotlin
val name: String? = null
val displayName = name ?: "Guest"
println(displayName) // Prints "Guest"
```
If I write the same thing using if-else, it takes 3-4 lines. So ?: is some kind of shorthand syntax? But I'm not sure when to use it and when it's better to stick with a regular check.
I also saw this strange code:
```kotlin
val length = text?.length ?: 0
```
Here, first comes ?. (safe call), then ?:. Is this even legal? And what happens if text is null?
Please explain how this operator works, how it differs from regular if-else, and whether there are
No answers yet.
Log in to leave an answer