2
\$\begingroup\$

I have a map whose values are case classes, and I want to access one parameter of that case class with a default value if they map doesn't contain the provided key.

myMap.get(myKey).map(_.valueParam).getOrElse(defaultParam)

intellij-scala suggests that this is a "simplifiable operation on collection” -- is there a more idiomatic way to write this?

*

Edit/Answer: The alternative approach would be to use

myMap.get(myKey).fold(defaultParam)(valueParam)
\$\endgroup\$

closed as off-topic by 200_success Nov 7 '14 at 17:39

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

  • 2
    \$\begingroup\$ Hi. Welcome to Code Review! We usually review more code than this. In particular, I would like to see where myMap is defined and loaded. As stands, this is more of a Stack Overflow question. Questions asking for help writing code are off-topic here. \$\endgroup\$ – Brythan Nov 7 '14 at 14:00
  • \$\begingroup\$ Got it, sorry about that! \$\endgroup\$ – cohoz Nov 8 '14 at 16:37
2
\$\begingroup\$

Map has a getOrElse option:

myMap.getOrElse(myKey,defaultParameter).valueParameter
\$\endgroup\$
  • \$\begingroup\$ You should rename defaultParameter since it is actually the container of the default parameter. \$\endgroup\$ – toto2 Nov 7 '14 at 21:09
  • \$\begingroup\$ This isn't exactly what I wanted (would rather not have to create an entire object when I just want to access a parameter) but perhaps that isn't possible to do any differently than in the question. In either case, I'll have to follow up elsewhere. \$\endgroup\$ – cohoz Nov 8 '14 at 17:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.