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?
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
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With