0

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...

2 Answers2

1

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
Ende Neu
  • 15,581
  • 5
  • 57
  • 68
  • or provide both functions in the same argument list: `def doSomethingGreat(succeed: Boolean)(f: => Unit, default: => Unit = noop): Unit` – Gabriele Petronella Aug 18 '14 at 23:54
  • Thanks Ende. That's a lot like what I ended up doing. I guess I was wondering if I could leave out the trailing parentheses entirely, though, and have Scala infer that I left out the default argument on purpose. It's nothing crucial, though. – LoudFlamingo Aug 19 '14 at 17:44
  • Yeah I actually thought that too, I didn't knew until I tried. – Ende Neu Aug 19 '14 at 17:49
-1

Try noop _ in your code, to properly reference such function definition.

cchantep
  • 9,118
  • 3
  • 30
  • 41