带有 Option 参数的二元运算符 [英] Binary operator with Option arguments

查看:46
本文介绍了带有 Option 参数的二元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Scala 中,如何定义两个 Option 参数的加法?具体来说,假设它们是 Int 类型的包装器(我实际上是在处理双精度映射,但这个例子更简单).

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
    }
  }

编辑添加:

在我的实际问题中,我添加了两个地图,它们是稀疏向量的替代品.所以 None 情况返回 Map[Int, Double] 而 + 实际上是一个 ++(在 stackoverflow.com/a/7080321/614684 上进行了调整)

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)

推荐答案

(根据要求在回答中重复上述评论)

您没有以正确的方式提取选项的内容.当您与 case Some(x) 匹配时,x 是选项内的值(type Int),您不会调用 get 就可以了.就做

You don't extract the content of the option the proper way. When you match with case Some(x), x is the value inside the option(type Int) and you don't call get on that. Just do

case Some(x) => x 

不管怎样,要内容还是要默认,a.getOrElse(0)更方便

Anyway, if you want content or default, a.getOrElse(0) is more convenient

这篇关于带有 Option 参数的二元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆