Scala empty default closure?

just a quick question I seem to be unable to find an answer to.

I have a method definition in Scala that looks like this:

def execute(goals: List[String],
            profiles: List[String] = List(),
            loggingCallback: (String) => Unit = { _ => }): Result = {
    // method body
    loggingCallback("a message")

I would like to know whether there is a better way to specify a default empty closure. The question is not about how to implement logging, this is just an example.


Your solution is fine. You could introduce a type alias for Function1[X, Unit]; use () as per Kevin’s answer, and drop unnecessary parens.

scala> type Effect[-A] = (A => Unit)
defined type alias Effect

scala> def foo(f: Effect[String] = _ => ()) = ()
foo: (f: (String) => Unit)Unit

You could also define a noop function:

scala> val noop = (a: Any) => ()
noop: (Any) => Unit = <function1>

scala> def foo(f: Effect[String] = noop) = ()

Source : Link , Question Author : Andreas Eisele , Answer Author : retronym

Leave a Comment