Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: Check if null and cast it directly

Tags:

android

kotlin

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

like image 290
iori24 Avatar asked Dec 02 '25 09:12

iori24


1 Answers

you can use

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

 }
like image 144
Saurabh Avatar answered Dec 05 '25 01:12

Saurabh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!