Swift 'if let' equivalent in Kotlin: how to safely unwrap Optional?
Hello colleagues! I recently switched from Swift to Kotlin and can't find a direct equivalent of the `if let` construct. In Swift I often wrote like this:
```swift
if let unwrappedValue = optionalValue {
print("Value exists: \(unwrappedValue)")
} else {
print("Value is nil")
}
```
This allowed safely unwrapping an Optional and using the value inside the block. In Kotlin, as I understand, instead of Optionals there are nullable types with a question mark (e.g., `String?`). But I can't figure out how to elegantly and safely check that a value is not null and immediately assign it to a new immutable variable. I tried using `?.let`, but it's not exactly what I want:
```kotlin
val optionalValue: String? = "Hello"
optionalValue?.let { unwrappedValue ->
println("Value
No answers yet.
Log in to leave an answer