In the class or object body, this works:
def a(s:String) {}
def a(s:Int) {}
But if it is placed inside another method, it does not compile:
def something() {
def a(s:String) {}
def a(s:Int) {}
}
Why is it so?
In C++, function overloading can only occur between members of the same class. Whereas in Java, overloading can occur, in addition to that, across two classes with inheritance relationship.
In java, method overloading is not possible by changing the return type of the method only because of ambiguity.
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 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.
Note that you can achieve the same result by creating an object:
def something() {
object A {
def a(s:String) {}
def a(i: Int) {}
}
import A._
a("asd")
a(2)
}
In your example, you define local functions. In my example, I'm declaring methods. Static overloading is allowed for objects, classes and traits.
I don't know why it's not allowed for local functions but my guess is that overloading is a possible source of error and is probably not very useful inside a code block (where presumably you can use different names for in that block scope). I assume it's allowed in classes because it's allowed in Java.
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