重载方法的 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 给出重载方法+需要结果类型
错误)
如果我将该方法更改为:
def +(i: Int): Rational = { new Rational(i) + this }
它有效...
Given this code:
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)
}
}
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 }
It works...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我在 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:
在这种情况下,它可以推断出正确的类型,但它还不够聪明。使用重载方法构建一些病态示例很容易,其中事情会变得非常混乱,所以我想这就是为什么 Scala 团队决定进行明确划分并要求返回类型的原因。这类似于递归方法,您也需要结果类型,即使编译器在许多情况下可以推断它。
In this case it could infer the right type, but it just isn't clever enough. It's easy to construct some pathological examples with overloaded methods where things get really messy, so I guess that's why the Scala team decided to make a clear cut and require the return type. This is similar to recursive methods, where you need the result type, too, even though the compiler could infer it in many cases.