In Scala, can you make an anonymous function have a default argument?

The boring, correct answer is no, you can't, but actually you kind of can, with the experimental single abstract method (SAM) synthesis in 2.11.

First you need to define your own SAM type with the default value for the apply method's parameter:

trait Func {
  def apply(name: String = "joe"): Boolean
}

Now you can use the function literal notation to define a Func (note that you'll need to have started the REPL with -Xexperimental for this step to work):

val f: Func = { (name: String) => name == "joe" }

Or just:

val f: Func = _ == "joe"

And then the usual stuff:

scala> f("joe")
res0: Boolean = true

scala> f("eoj")
res1: Boolean = false

And the punchline:

scala> f()
res2: Boolean = true

It's not exactly the syntax you're asking for, and there are no promises that this will ever leave experimental status, and even if it does, default arguments may not be supported—but I still think it's pretty neat that it works now.


To expand on "The boring, correct answer is no" in Travis Brown's answer:

Functions (i.e. objects of FunctionN[...] type) can't have default arguments in Scala, only methods can. Since anonymous function expressions produce functions (and not methods), they can't have default arguments.