is there a better way to write the code below?
val t = map.get('type).getOrElse("");
if (t != "") "prefix" + t;
be interested in inline code something like
val t = map.get('type).getOrElse("").????
getOrElse() Method: This method is utilized in returning either a value if it is present or a default value when its not present. Here, For Some class a value is returned and for None class a default value is returned.
Scala Map get() method with exampleThe get() method is utilized to give the value associated with the keys of the map. The values are returned here as an Option i.e, either in form of Some or None. Return Type: It returns the keys corresponding to the values given in the method as argument.
We can insert new key-value pairs in a mutable map using += operator followed by new pairs to be added or updated.
Map
has its own getOrElse
method, so you can just write the following:
val t = map.getOrElse('type, "")
Which accomplishes the same thing as the definition of t
in your first example.
To address your comment: If you know your map will never contain the empty string as a value, you can use the following to add the "prefix"
:
map.get('type).map("prefix" + _).getOrElse("")
Or, if you're using Scala 2.10:
map.get('type).fold("")("prefix" + _)
If your map can have ""
values, this version will behave a little differently than yours, since it will add the prefix to those values. If you want exactly the same behavior as your version in a one-liner, you can write the following:
map.get('type).filter(_.nonEmpty).map("prefix" + _).getOrElse("")
This probably isn't necessary, though—it sounds like you don't expect to have empty strings in your map.
It's also worth noting that, in certain cases, you can replace multiple common .getOrElse
usages with one .withDefaultValue
call.
val map = complexMapCalculation().withDefaultValue("")
val t = map('type)
I wouldn't say this is something that should be done every time, but it can be handy.
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