1

I oftentimes face the following problem:

val b = a match {
  case Some(a) => "1"
  case None => "n"
}
val c = a match {
  case Some(a) => "2"
  case None => "n"
}

Obviously, the match is executed twice even though it is only necessary once. How can I make sure the compiler takes this into account?

2 Answers 2

8

I don't think there will be any performance gain but you can write your code like this:

val (b, c) = a match {
  case Some(a) => ("1","2)
  case None => ("n", "n")
}
Sign up to request clarification or add additional context in comments.

8 Comments

Looks good, but what if the after=>-parts are multilined? How would I handle this?
For the code written it's a performance loss because the match is really fast, but it's nonetheless a good way to reflect that two new values depend on one old one. So it's probably the superior pattern to use in the absence of performance concerns (or with something that is slow to match).
Just my opinion, I think that pattern matching an option is usually unnecessarily verbose. What about doing that ? a.map(_ => ("1", "2")).getOrElse( ("n","n") )
+1... I want to do one more +1 for the username and the icon :)
@vtheron: For me, pattern matching gives a well-arranged structure to the code. How would you write multilined code with getOrElse?
|
1

Matches can be extremely fast--comparable to an if-statement. Don't worry about doing the work twice unless it's a difficult match.

It's slightly easier to match a default than another case, so if you really don't need the parameter your best bet is

val b = a match { case None => "n"; case _ => "1" }
val c = a match { case None => "n"; case _ => "2" }

This will often even outperform a mutable solution like

var b,c = "n"
a match { case Some(_) => b = "1"; c = "2"; case _ => }

and will certainly outperform any tuple-creation.

If the match is a time-consuming one then you have to store your results and return them in a tuple or other suitable data structure, as om-nom-nom has already demonstrated. This may also be more clear, depending on context.

1 Comment

Typing it twice is also twice the work. :) Thanks for the reminder to be aware of extra allocations, as a matter of performance style (as a habit, something to do way in advance of profiling).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.