Rajeev
Rajeev

Reputation: 5002

Whats wrong with Scala overload method

Below code throws compilation error in worksheet

 def joiner(strings:List[String], separator:String):String = strings.mkString(separator)
  def joiner(strings:List[String]):String = joiner(strings, "  ")

  joiner(List("sdsdfsd", "sdsd"))

Error :

Error:(12, 120) too many arguments for method joiner: (strings: List[String])String
println("joiner: " + MacroPrinter211.printGeneric({import inst$A$A._ ;def joiner(strings:List[String]):String = joiner(strings, "  ") }).replace("inst$A$A.", ""))
                                                                                                                      ^

I have overloaded joiner method. Why it is giving error that too many arguments?

Upvotes: 4

Views: 249

Answers (2)

Archeg
Archeg

Reputation: 8462

Your code works correctly if you put it inside a class or object, because a class or an object can have overloaded methods in scala.

But if you write your code in REPL - these are not methods, but functions. And functions cannot be overloaded. So you should put these inside an object or class or use default parameters as suggested by @StuartMcvean

Update As @Travis properly corrects my answer I was wrong about the reason of the things happening here. It looks like REPL (and worksheet as well) does not process it correctly because of the mechanics of how it processes methods.

As I understood (I hope I'm correct this time), this is because REPL needs to change one method to the other one, because REPL allows you to define methods with not compatible signatures, replacing the old method (for example methods that differ only by return values)

If you try to paste your code with :paste (not sure what's the equivalent for worksheet) - it processes correctly

Upvotes: 6

StuartMcvean
StuartMcvean

Reputation: 450

In scala you can provide default parameters. This will let you do the following:

def joiner(strings:List[String], separator:String = " "): String =
  strings.mkString(separator)

joiner(List("sdsdfsd", "sdsd"))

Upvotes: 3

Related Questions