4

我想要一个带有 2 个按名称调用参数的方法,其中一个是可选的,但仍然在不带括号的情况下调用它。因此,您可以执行以下任一操作:

transaction { ... }

或者

transaction { ... } { ... }

我尝试(并解决了):

def transaction(body: => Unit) { transaction(body, {}) }
def transaction(body: => Unit, err: => Unit) { ... } // Works by transaction({ ... },{ ... })

这显然不同于(出于我不知道的原因):

def transaction(body: => Unit, err: => Unit = {}) { ... }

而我希望的那个会起作用(但我猜不是因为第一个参数列表是相同的)。

def transaction(body: => Unit) { transaction(body)() }
def transaction(body: => Unit)(err: => Unit) { ... }

您将如何使用可选的第二个按名称调用参数的概念?

4

1 回答 1

0

它与默认参数的工作方式有关。注意:

scala> def f(x:Int = 5) = println(x)
f: (x: Int)Unit

scala> f
<console>:9: error: missing arguments for method f in object $iw;
follow this method with `_' if you want to treat it as a partially applied function
              f
              ^

scala> f()
5

具有默认参数的方法总是需要调用 ()。

因此,要使用两个参数列表和一个默认参数工作,我们需要:

scala> def transaction(body: => Unit)(err: => Unit = { println("defult err")}) { body; err; }
transaction: (body: => Unit)(err: => Unit)Unit

scala> transaction { println("body") } 
<console>:9: error: missing arguments for method transaction in object $iw;
follow this method with `_' if you want to treat it as a partially applied function
              transaction { println("body") } 

scala> transaction { println("body") } ()
body
defult err
于 2012-07-05T15:32:55.167 回答