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