简体   繁体   中英

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

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

尝试在代码中使用noop _ ,以正确引用此类函数定义。

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