简体   繁体   中英

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 func s) pass in a non-anonymous function?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM