I have the following HashMap:
val myHashMap: HashMap<key, ValueClass>
where:
data class ValueClass(
var a: Long = 0,
var b: Long = 0
)
I'd like to use the myHashMap as follows: if myHashMap, does not contain the key x, create a new ValueClass and insert it into myHashMap, then myHashMap[x].a = newValue.
What is the cleanest way to do so? In Java, I would have had:
if (!myHashMap.containsKey("x"))
{
map.put("x", new ValueClass());
}
map.get("x").a = newValue;
Use MutableMap#getOrPut
myMap.getOrPut("key") { "default_value" }
Another alternative:
val foo = map["x"] ?: ValueClass().also { map["x"] = it }
foo.x = newValue
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