In Scala, is it possible to make an anonymous function a default argument?

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

I expected this to work the same way:
scala> val test: String => Boolean = { (name: String = "joe") => true } <console>:1: error: ')' expected but '=' found.

+6
source share
3 answers

The boring, correct answer is no, you canโ€™t, but in fact you can, with experimental synthesis of one abstract method (SAM) in 2.11.

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

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

Now you can use the function conventions to define Func (note that for this step you need to run REPL with -Xexperimental ):

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

Or simply:

 val f: Func = _ == "joe" 

And then the usual stuff:

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

And pointling:

 scala> f() res2: Boolean = true 

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

+13
source

To go to โ€œBoring, the correct answer is no,โ€ in Travis Brown's answer:

Functions (that is, objects of type FunctionN[...] ) cannot have default arguments in Scala, only methods can. Because anonymous function expressions produce functions (not methods), they cannot have default arguments.

+4
source

This is a bit dirty solution, I think using currying

def testDef(nameDef: String)(name2: String): Boolean = { val name3 = if ( name2 != "") name2 else nameDef //use name3 for your logic true } // "> testDef: (name: String) (name2: String) Boolean

Wrap the testDef method to save the default value as shown below.

var test = test("joe")_ // "> test: String => Boolean = function1

test("fun") // "fun" will be used as name3
test("") // "joe" will be used as name3

0
source

Source: https://habr.com/ru/post/973627/


All Articles