How to access value of map with a key if key was not found in scala? -
assume have
var mp = map[string,string]() ..... val n = mp("kk")
the above throw runtime error in case key "kk" did not exist.
i expected n null in case key did not exist. want n null if key did not exist.
what proper way handle situation in scala short code sample?
first of all, don't want null, that's sign of bad coding in scala. want n of type option[string], says value either string or missing. right way .get() method on map
val n = mp.get("kk")
if need null (for interop java libraries, example), can use .getorelse()
val n = mp.getorelse("kk", null)
Comments
Post a Comment