Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overload scala function apply methods

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
}
like image 255
eptx Avatar asked Sep 08 '11 04:09

eptx


2 Answers

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
}
like image 55
Daniel C. Sobral Avatar answered Sep 28 '22 08:09

Daniel C. Sobral


2 little changes:

  • Use ( instead of { when calling apply:

    apply(.......)

  • Use ( around the arg to an implicit function:

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

like image 23
Owen Avatar answered Sep 28 '22 09:09

Owen