First case
save(throw new RuntimeException("boom!")) _
According to the โScala Linkโ (ยง6.7), an underscore is used instead of the argument list, and the expression is converted to
val f: (Boolean) => Unit = save(throw new RuntimeException("boom!"))
where the first def save argument is immediately evaluated.
The expression e_ is well-formed if e is of a method type or if e is a call-by-name. If e is a method with parameters, e_ represents e is converted to a function type by eta extension (ยง6.26.5). If e is a parameterless method or a call by name is a parameter of type => T, e_ represents a function of type () => T, which evaluates e when it is applied to empty parameterlist ().
In order for everything to work as you expect, some changes are needed:
scala> def save(f:() => Any)(run:Boolean) { if (run) { println("running f"); f() } else println("not running f") } save: (f: () => Any)(run: Boolean)Unit scala> val f = save(() => throw new RuntimeException("boom!")) _ f: (Boolean) => Unit = <function1> scala> f(true) running f java.lang.RuntimeException: boom! at $anonfun$1.apply(<console>:6)
Second case
save(throw new RuntimeException("boom!"))(_)
According to the โScala Linkโ (ยง6.23), when a placeholder is used as a substitute for an argument, the expression is converted to
val f: (Boolean) => Unit = save(throw new RuntimeException("boom!"))(_)
Vasil Remeniuk
source share