Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it doesn't allowed to overload methods inside methods (e.g. overloaded closures)?

A minimized example is the following:

object Main extends App { 
  def f = {
    def giveMeBigDecimal(x: String) = BigDecimal(x)
    def giveMeBigDecimal(x: Double) = BigDecimal(x)
    (giveMeBigDecimal("1.0"), giveMeBigDecimal(1.0))
  }
}

Scala 2.9.2 compiler keep saying me that method giveMeBigDecimal is defined twice
I know how can I workaround this, but curious why such limitation exists.

like image 747
om-nom-nom Avatar asked Sep 20 '12 14:09

om-nom-nom


People also ask

Why methods are not overloaded based on return type?

Overloading is the mechanism of binding the method call with the method body dynamically based on the parameters passed to the method call. ... It is not possible to decide to execute which method based on the return type, therefore, overloading is not possible just by changing the return type of the method.

Why does Java not support method overloading?

As said in previous answers, java does not support method overloading with different return type and same arguments. This is because, it has to determine which method to use at the compile time itself. To remove the ambiguity, they designed the method overloading technique like this.

Which methods Cannot be overloaded in Java?

Can we overload methods that differ only by static keyword? We cannot overload two methods in Java if they differ only by static keyword (number of parameters and types of parameters is the same).

Can we overload method in different class?

Usually, method overloading happens inside a single class, but a method can also be treated as overloaded in the subclass of that class — because the subclass inherits one version of the method from the parent class and then can have another overloaded version in its class definition.


1 Answers

It's a Scala's implementation detail which (unfortunately) made its way to the spec. Scala implements local methods as variables with closure type and it isn't allowed to have two variables with the same name in the same method.

like image 65
Konstantin Solomatov Avatar answered Dec 20 '22 09:12

Konstantin Solomatov