Search code examples
scalaanonymous-function

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


This works:

scala>  def test(name: String = "joe"): Boolean = true 
test: (name: String)Boolean

I expected this to work in the same way:

scala>  val test: String => Boolean = { (name: String = "joe") => true }

console>:1: error: ')' expected but '=' found.

Solution

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