Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala type inference on overloaded method

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...

like image 590
Dzhu Avatar asked Oct 21 '11 06:10

Dzhu


People also ask

Does Scala have type inference?

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 overloaded method in Scala?

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.

When would you not use method overloading?

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.


1 Answers

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.
like image 88
Barak Itkin Avatar answered Sep 18 '22 15:09

Barak Itkin