Reputation: 4091
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?
Upvotes: 1
Views: 271
Reputation: 167891
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.
Upvotes: 1
Reputation: 62835
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")
}
Upvotes: 8