gpt4 book ai didi

Scala 对重载方法的类型推断

转载 作者:行者123 更新时间:2023-12-03 19:54:51 25 4
gpt4 key购买 nike

鉴于此代码:

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 给出 overloaded method + needs result type 错误)

如果我将该方法更改为:
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.

关于Scala 对重载方法的类型推断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7845569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com