Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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.

share|improve this question
2  
You know the difference between function and method in Scala? –  sschaef Jan 23 '13 at 15:39
    
@sschaef: thanks for the hint. I did mean method. Will edit my question for asking method overloading. –  Codism Jan 23 '13 at 15:43

1 Answer 1

up vote 4 down vote accepted

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.

share|improve this answer
    
I got the wrong impression because of some other syntax error when I tried it. After seeing sschaef's comment, I tried again and the code compiles. Thanks for clarification. –  Codism Jan 23 '13 at 16:15

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.