In scala, how do I define addition over two Option arguments? Just to be specific, let’s say they’re wrappers for Int types (I’m actually working with maps of doubles but this example is simpler).
I tried the following but it just gives me an error:
def addOpt(a:Option[Int], b:Option[Int]) = {
a match {
case Some(x) => x.get
case None => 0
} + b match {
case Some(y) => y.get
case None => 0
}
}
Edited to add:
In my actual problem, I’m adding two maps which are standins for sparse vectors. So the None case returns Map[Int, Double] and the + is actually a ++ (with the tweak at stackoverflow.com/a/7080321/614684)
(Repeating comment above in an answer as requested)
You don’t extract the content of the option the proper way. When you match with
case Some(x),xis the value inside the option(typeInt) and you don’t callgeton that. Just doAnyway, if you want content or default,
a.getOrElse(0)is more convenient