Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 920
dor506 Avatar asked May 29 '17 07:05

dor506


People also ask

Which operator can safely cast a value in Kotlin?

"Safe" (nullable) cast operator

What is safe casting in Kotlin?

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.

How do you cast with Kotlin?

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.

What is smart cast in Kotlin?

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.


2 Answers

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) {     ... } 
like image 134
Alexander Udalov Avatar answered Oct 09 '22 21:10

Alexander Udalov


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  
like image 31
hasen Avatar answered Oct 09 '22 20:10

hasen