gpt4 book ai didi

scala - 在Scala中,您可以使匿名函数具有默认参数吗?

转载 作者:行者123 更新时间:2023-12-04 09:18:13 24 4
gpt4 key购买 nike

这有效:

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

我希望这可以相同的方式工作:
scala>  val test: String => Boolean = { (name: String = "joe") => true }

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

最佳答案

无聊,正确的答案是“否”,您不能,但实际上您可以使用2.11中的实验性single abstract method (SAM) synthesis

首先,您需要使用apply方法的参数的默认值定义自己的SAM类型:

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

现在,您可以使用函数文字符号来定义 Func(请注意,您必须先使用 -Xexperimental启动REPL才能执行此步骤):
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

这不完全是您所要求的语法,并且也没有保证它会离开实验状态,即使是这样,也可能不支持默认参数,但是我仍然认为它很整洁,现在就可以使用。

关于scala - 在Scala中,您可以使匿名函数具有默认参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25234682/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com