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
"Safe" (nullable) cast operator
Kotlin provides a safe cast operator as? for safely cast to a type. It returns a null if casting is not possible rather than throwing an ClassCastException exception.
In Smart Casting, we generally use is or !is an operator to check the type of variable, and the compiler automatically casts the variable to the target type, but in explicit type casting we use as operator. Explicit type casting can be done using : Unsafe cast operator: as.
Smart cast is a feature in which the Kotlin compiler tracks conditions inside of an expression. If the compiler finds a variable that is not null of type nullable then the compiler will allow to access the variable.
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) { ... }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With