Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats wrong with Scala overload method

Tags:

scala

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?

like image 327
Rajeev Avatar asked Jan 06 '23 18:01

Rajeev


2 Answers

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

like image 177
2 revs Avatar answered Jan 16 '23 01:01

2 revs


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"))
like image 20
StuartMcvean Avatar answered Jan 16 '23 02:01

StuartMcvean