加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala类型推论重载方法

发布时间:2020-12-16 09:23:32 所属栏目:安全 来源:网络整理
导读:给出这个代码: class Rational(n: Int,d: Int) { require(d != 0) private val g = gcd(n.abs,d.abs) val numerator = n / g val denominator = d / g def this(n: Int) = this(n,1) override def toString = numerator + "/" + denominator def +(r: Ratio
给出这个代码:

class Rational(n: Int,d: Int) {
  require(d != 0)
  private val g = gcd(n.abs,d.abs)
  val numerator = n / g
  val denominator = d / g

  def this(n: Int) = this(n,1)

  override def toString = numerator + "/" + denominator

  def +(r: Rational) = new Rational(numerator * r.denominator + r.numerator * denominator,denominator * r.denominator)

  def *(r: Rational) = new Rational(numerator * r.numerator,denominator * r.denominator)

  def +(i: Int) = new Rational(i) + this

  private def gcd(a: Int,b: Int) : Int = {
    if (b == 0) a else gcd(b,a % b)
  }

}

为什么Scala能够推断(i:Int)返回一个Rational数字? (fsc给出重载方法需要结果类型错误)

如果我将该方法更改为:

def +(i: Int): Rational = { new Rational(i) + this }

有用…

解决方法

我在Scala邮件列表中发现了一条与 here完全相同的问题的线程.这里的答案解释了为什么需要给出返回类型.在调查了一点以后,我也发现这个: When is a return type required for methods in Scala.如果我应该引用答案:

When Explicit Type Annotations Are Required.

In practical terms,you have to provide explicit type annotations for the following situations:

Method return values in the following cases:

  • When you explicitly call return in a method (even at the end).
  • When a method is recursive.
  • When a method is overloaded and one of the methods calls another. The calling method needs a return type annotation.
  • When the inferred return type would be more general than you intended,e.g.,Any.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读