iadcialim24
iadcialim24

Reputation: 4015

Kotlin: Check if null and cast it directly

In my android app, I have a map of <String, Any?> and the value of the key could be an Int or String or null.

Currently, I do it like this:

map[key]?.let {
    val value = it as Int
    // use value here
}

If there a way to have a shortcut like Swift

if let value = map[key] as? Int {

}

So it's like a single line to check for nullity and cast it on the spot

Upvotes: 3

Views: 558

Answers (1)

Saurabh
Saurabh

Reputation: 1245

you can use

 (map[key] as? Int)?.let {

 }

Upvotes: 6

Related Questions