簡體   English   中英

可選的不帶括號的call-by-name參數

[英]Optional call-by-name parameter without parentheses

我想要一個帶有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參數的概念?

它與默認參數的工作方式有關。 注意:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM