2012-07-04 25 views
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 = {}) { ... } 

而我希望的那个w将工作(但我猜并不是因为第一个参数列表是相同的)。

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

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

+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