Hi all. I was wondering if there’s a nice way to d...
# announcements
b
Hi all. I was wondering if there’s a nice way to do something like:
Copy code
val myObject: MyClass? = map.ifKeyPresent("xyz) { return MyClass(it }.orElse { null }
So, basically, if a map contains the key, convert the value of that key to a different type, and if it’s not there, return something else, for example
null
. Does something like this exist?
v
Copy code
val myObject = map["xyz"]?.let { MyClass(it) }
b
Oh wow, that simple? Thanks!
v
won't work if your map is <key, value?>
caveat
like, <string, int?>
b
Fair enough. The actual use case was actually Python, but I was wondering what the Kotlin equivalent was.
t
if null-Values are possible and you really want to check if the key exists, you could do
Copy code
val myObject = if ("xyz" in map) MyClass(map["xyz"]) else null
but I guess that's a really rare case
m
@vineethraj49 true, but since
existence with null
and
non-existence
encapsulate the same meaning, one should ask themselves if making a map with nullable values is what you want to begin with.