Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala better syntax for map getOrElse

Tags:

scala

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("").????
like image 239
pbaris Avatar asked Sep 20 '12 00:09

pbaris


People also ask

What does getOrElse do in Scala?

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.

How do you access map elements in Scala?

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.

How do you add a value to a map in Scala?

We can insert new key-value pairs in a mutable map using += operator followed by new pairs to be added or updated.


2 Answers

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.

like image 179
Travis Brown Avatar answered Oct 13 '22 15:10

Travis Brown


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.

like image 26
Dave Griffith Avatar answered Oct 13 '22 16:10

Dave Griffith