I would like a method with 2 call-by-name parameters, where one is optional, but still call it without parentheses. So you can do either:
transaction { ... }
or
transaction { ... } { ... }
I tried (and settled for):
def transaction(body: => Unit) { transaction(body, {}) }
def transaction(body: => Unit, err: => Unit) { ... } // Works by transaction({ ... },{ ... })
Which apparently is different from (for a reason I don't know):
def transaction(body: => Unit, err: => Unit = {}) { ... }
And the one I hoped would work (but I guess doesn't because the first parameter list is the same).
def transaction(body: => Unit) { transaction(body)() }
def transaction(body: => Unit)(err: => Unit) { ... }
How would you use the concept of a optional second call-by-name parameter?
It has to do with how default parameter works. Notice:
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
Methods with default parameters always requires the () to be invoked.
So, to make the case with two parameters lists and a default parameter work we need:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.