How to overload scala application methods

As the following: scala loan template, optional function parameter

What is the correct syntax for moving the withLoaner parameter to overloaded application methods? I tried several versions of the following unsuccessfully. Also, any understanding of my mistake is conceptually very much appreciated.

def withLoaner = new { def apply(n:Int, op: Int => String):String = (1 to n).map(op).mkString("\n") def apply(n:Int, op: () => String):String = apply{n, i:Int => op()} // no compile def apply(op: () => String):String = apply{1, i:Int => op()} // no compile } 
+6
source share
2 answers

When passing multiple parameters, you must use parentheses around them. Using {} works only for single parameters.

Also, when using function literals, if you specify a type, you must put all the parameters of the functions in parentheses.

So,

 def withLoaner = new { def apply(n:Int, op: Int => String):String = (1 to n).map(op).mkString("\n") def apply(n:Int, op: () => String):String = apply(n, i => op()) // no type on i def apply(op: () => String):String = apply(1, (i: Int) => op()) // parenthesis around parameters } 
+11
source

2 small changes:

  • Use ( instead of { when calling apply :

    apply (.......)

  • Use ( around arg for an implicit function:

    apply (1, (i: Int) => op ())

+3
source

Source: https://habr.com/ru/post/896843/


All Articles