Scala – Method Overloading Explained

scala

I know method overload is not allowed in Scala and I have read some posts regarding the reasons. But still, I see some functions overloaded in Scala library (example: println). I want to know how it is done and if I can use the same mechanism to some of my methods.

Best Answer

Functions cannot be overloaded in Scala, that is correct. But println is not a function, it is a method, and methods most definitely can be overloaded.

I'm not sure what you mean by "How it is done". It is done the exact same way that you do it in every other language that supports overloading. If you want two definitions of a method with different types you write two definitions with different types:

def foo(arg: Int)    { println("I am overloaded for Int.")    }
def foo(arg: String) { println("I am overloaded for String.") }

foo(42)
// I am overloaded for Int.

foo("Hello")
// I am overloaded for String.

foo(1.0)
// error: overloaded method value foo with alternatives:
//  (arg: String)Unit <and>
//  (arg: Int)Unit
// cannot be applied to (Double)
//                  foo(1.0)
//                  ^

The reason why function overloading isn't supported is simple: technically speaking, the term doesn't even make sense, since "overloading" basically means (very broadly) "different bindings for the same name depending on context". But functions don't have a name, so the whole concept of having different implementations bind to the same name is nonsensical.

Related Topic