我想要一个带有2个call-by-name参数的方法,其中一个是可选的,但仍然没有括号调用它。所以你可以这样做:
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) { ... }
您如何使用可选的第二个call-by-name参数的概念?
答案 0 :(得分: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