As a follow on to: scala loan pattern, optional function param
What would the proper syntax be to move the withLoaner param to overloaded apply methods? I've tried several versions of the following unsuccessfully. Also, any insights into my error conceptually very 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
}
When passing multiple parameters, you must use parenthesis around them. Using {} only works for single parameters.
Also, when using function literals, if you specify type, you have to put all of the functions parameters inside parenthesis.
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
}
2 little changes:
Use (
instead of {
when calling apply
:
apply(.......)
Use (
around the arg to an implicit function:
apply(1, (i:Int) => op())
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