Dzh*_*zhu 15 scala type-inference
鉴于此代码:
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)
}
}
Run Code Online (Sandbox Code Playgroud)
为什么scala不能推断+(i:Int)返回一个Rational数?(fsc给出overloaded method + needs result type错误)
如果我将该方法更改为:
def +(i: Int): Rational = { new Rational(i) + this }
Run Code Online (Sandbox Code Playgroud)
有用...
Bar*_*kin 26
我在scala邮件列表中找到了一个与此处完全相同的问题.那里的答案解释了为什么需要给出返回类型.在进一步研究之后,我也发现了这一点:Scala中方法何时需要返回类型.如果我应该从那里引用答案:
何时需要显式类型注释.
实际上,您必须为以下情况提供显式类型注释:
方法在以下情况下返回值:
- 当您在方法中显式调用return时(即使在结尾处).
- 当一个方法是递归的.
- 当方法重载并且其中一个方法调用另一个方法时.调用方法需要返回类型注释.
- 当推断的返回类型比您预期的更通用时,例如,
Any.
| 归档时间: |
|
| 查看次数: |
4153 次 |
| 最近记录: |