Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why method overloading does not work inside another method?

Tags:

scala

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?

like image 476
Rogach Avatar asked Sep 26 '11 03:09

Rogach


People also ask

Can method overloading be done in different classes in java?

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.

When method overloading is not possible?

In java, method overloading is not possible by changing the return type of the method only because of ambiguity.

Can method overloading be done in different classes?

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.

Why method overloading is not possible by changing the return type of method only explain with proper java programming example?

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.


1 Answers

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.

like image 126
huynhjl Avatar answered Nov 22 '22 06:11

huynhjl