dor506
dor506

Reputation: 5404

Kotlin - equivalence to Swift's combination of "if let + cast"

I'm trying to find out how to achieve the combination of "if let + cast" in kotlin:

in swift:

if let user = getUser() as? User {
   // user is not nil and is an instance of User
}

I saw some documentation but they say nothing regarding this combination

https://medium.com/@adinugroho/unwrapping-sort-of-optional-variable-in-kotlin-9bfb640dc709 https://kotlinlang.org/docs/reference/null-safety.html

Upvotes: 33

Views: 16468

Answers (5)

Djangow
Djangow

Reputation: 391

What about this one?

val user = getUser() ?: return

Upvotes: 5

mgonzalez
mgonzalez

Reputation: 107

In Kotlin you can use the let:

val user = getUser()?.let { it as? User } ?: return

This solution is closest to guard but it may be useful.

Upvotes: 7

Alexander Udalov
Alexander Udalov

Reputation: 32776

One option is to use a safe cast operator + safe call + let:

(getUser() as? User)?.let { user ->
    ...
}

Another would be to use a smart cast inside the lambda passed to let:

getUser().let { user ->
    if (user is User) {
        ...
    }
}

But maybe the most readable would be to just introduce a variable and use a smart cast right there:

val user = getUser()
if (user is User) {
    ...
}

Upvotes: 45

hasen
hasen

Reputation: 166122

Kotlin can automatically figure out whether a value is nil or not in the current scope based on regular if statements with no need for special syntax.

val user = getUser()

if (user != null) {
    // user is known to the compiler here to be non-null
}

It works the other way around too

val user = getUser()

if (user == null) {
    return
}

// in this scope, the compiler knows that user is not-null 
// so there's no need for any extra checks
user.something 

Upvotes: 8

nhaarman
nhaarman

Reputation: 100378

In Kotlin you can use:

(getUser() as? User)?.let { user ->
  // user is not null and is an instance of User
}

as? is a 'safe' cast operator that returns null instead of throwing an error on failure.

Upvotes: 4

Related Questions