1

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?

2 Answers 2

3

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 
Sign up to request clarification or add additional context in comments.

2 Comments

I think your words aren't quite right in the parens. the underscore means "turn me into a function". The two ways are the same. Not sure anyone would use the first way, but if they did, they'd use parens at the invocation for style. scala-lang.org/files/archive/spec/2.11/…
thanks for the comments, actually that someone who does it the first way is me, because the second way feels less "intuitive".
3

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()) }); 

1 Comment

The first statement is wrong, in that it works without the overload. The eta-expand happens if it expects a func, but you can't say that without picking one of the overloaded symbols first.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.