mattelacchiato
mattelacchiato

Reputation: 416

Scala: Overloaded function with function as parameter

Given an overloaded function, with one taking a function as parameter. This parameter-function takes no arguments:

def func(param: () => Unit): Unit = {
  param()
}

def func(param: Int): Unit = {
  println(param)
}

While calling func with an anonymous function works perfect:

func(() => println("it works"))

Using a plain function fails:

def functionAsParam(): Unit = {
  println("it works")
}

func(functionAsParam)

Obviously, Scala evaluates functionAsParam and don't pass the function itself to func. Question: How can I (as a user of a library which provides funcs) pass in a non-anonymous function?

Upvotes: 1

Views: 427

Answers (2)

Ashalynd
Ashalynd

Reputation: 12563

There are several ways to do this. Either you explicitly pass the function as parameter:

scala> func(() => functionAsParam)
it works

scala> func (functionAsParam _ )
it works

(These two cases are slightly different though, in the sense that in the first example, you construct new anonymous function with your other function, and in the second example, you indicate that this function should not yet be evaluated, by adding _)

Or you create a variable which is a function and pass it along:

val fval = () => println("It works") 
scala> func(fval)
It works

Upvotes: 3

4lex1v
4lex1v

Reputation: 21547

The error comes from the fact that you defined a method, but your func expects a function. Yeah, there is a problem with overloading in scala (in other areas as well). To fix it you need manually convert your method into a function (it's called eta-expantion):

func(functionAsParam _)

If you turn on -Xprint:typer you'll see that scalac expands you method into a function:

val res4: Unit = func({
  (() => functionAsParam())
});

Upvotes: 3

Related Questions