Reputation: 5404
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
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
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
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
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