Scala 对重载方法的类型推断 [英] Scala type inference on overloaded method

查看:43
本文介绍了Scala 对重载方法的类型推断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于此代码:

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) 返回一个有理数?(fsc 给出重载方法+需要结果类型错误)

why isn't scala able to infer that +(i: Int) returns a Rational number? (fsc gives overloaded method + needs result type error)

如果我将该方法更改为:

if i change that method to:

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

它有效...

推荐答案

我在 Scala 邮件列表中发现了一个帖子,其中有完全相同的问题 此处.那里的答案解释了为什么需要提供返回类型.在进一步调查后,我还发现了这一点:何时是 Scala 中方法所需的返回类型.如果我应该引用那里的答案:

I found a thread in the scala mailing list with exactly the same question here. The answers there explains a bit why is it required to give the return type. After investigating a bit more I also found this: When is a return type required for methods in Scala. If I should quote the answer from there:

需要显式类型注释时.

实际上,您必须为以下情况提供显式类型注释:

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

以下情况下的方法返回值:

Method return values in the following cases:

  • 当您在方法中显式调用 return 时(甚至在最后).
  • 当一个方法是递归的.
  • 当一个方法被重载并且其中一个方法调用另一个方法时.调用方法需要返回类型注释.
  • 当推断的返回类型比您预期的更通用时,例如 Any.

这篇关于Scala 对重载方法的类型推断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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