Rogach
Rogach

Reputation: 27270

Why method overloading does not work inside another method?

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?

Upvotes: 12

Views: 199

Answers (1)

huynhjl
huynhjl

Reputation: 41656

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.

Upvotes: 10

Related Questions