Search code examples
scaladefault-parametersfunction-parameter

Scala default function literal parameter


In scala is it possible to provide a default value for a parameter that is a function?

For example, in my code I have something like this.

def noop(): Unit = {}

def doSomethingGreat(succeed: Boolean)(f: => Unit)(default: => Unit = noop): Unit = {
  if (success) {
    f
  } else {
    default
  }
}

When I try calling doSomethingGreat and I leave out a parameter for default, though, I get an error saying that I didn't pass in enough parameter. Any help?

So far, my workaround is to explicitly pass in a no-op function as the third parameter, but that defeats the purpose of having a default there in the first place...


Solution

  • You simply need to add parenthesis to your method invocation and scala will pick up the default function:

    scala>  def noop(): Unit = { println(567) }
    noop: ()Unit
    
    scala>   def doSomethingGreat(succeed: Boolean)(f: => Unit)(default: => Unit = noop): Unit = {
         |     if (succeed) {
         |       f
         |     } else {
         |       default
         |     }
         |   }
    doSomethingGreat: (succeed: Boolean)(f: => Unit)(default: => Unit)Unit
    
    scala>   doSomethingGreat(succeed = true)(println(123))()
    123
    
    scala>   doSomethingGreat(succeed = false)(println(123))()
    567