在 Scala 中,你能让匿名函数有一个默认参数吗? [英] In Scala, can you make an anonymous function have a default argument?

查看:19
本文介绍了在 Scala 中,你能让匿名函数有一个默认参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这有效:

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.

推荐答案

无聊的正确答案是否定的,你不能,但实际上你可以,用实验性的 2.11 中的单一抽象方法 (SAM) 合成.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆