在Scala中,您可以使匿名函数具有默认参数吗? [英] In Scala, can you make an anonymous function have a default argument?
问题描述
这有效:
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.
推荐答案
无聊,正确的答案是不可以",你不能,但是实际上你可以,通过实验性的
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.
首先,您需要使用apply
方法参数的默认值定义自己的SAM类型:
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
}
现在,您可以使用函数文字表示法来定义Func
(请注意,您需要使用-Xexperimental
启动REPL,此步骤才能起作用):
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" }
或者只是:
val f: Func = _ == "joe"
然后是通常的东西:
scala> f("joe")
res0: Boolean = true
scala> f("eoj")
res1: Boolean = false
妙语:
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.
这篇关于在Scala中,您可以使匿名函数具有默认参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!