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...
The Scala compiler can infer the types of expressions automatically from contextual information. Therefore, we need not declare the types explicitly. This feature is commonly referred to as type inference. It helps reduce the verbosity of our code, making it more concise and readable.
What is Scala Method Overloading? Scala Method overloading is when one class has more than one method with the same name but different signature. This means that they may differ in the number of parameters, data types, or both. This makes for optimized code.
Overloading is a powerful feature, but you should use it only as needed. Use it when you actually do need multiple methods with different parameters, but the methods do the same thing. That is, don't use overloading if the multiple methods perform different tasks.
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:
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With