Reputation: 435
1) How is this construction called? Cannot google it.
2) Why it doesn't work? I expect message be printed.
class A {
def m() {
println("m()")
}
}
object Main {
def main(args: Array[String]) {
val fun = (_: A).m _
fun(new A())
}
}
Upvotes: 1
Views: 194
Reputation: 26486
As om-nom-nom says, the conversion of methods to functions is called "partial application." It can be expressed explicitly by using underscore(s) as "arguments" to a method or automatically by the compiler when the available type information is sufficient for it to infer that a method name used in a place where a function is required can be partially applied to produce the required function.
Now, for your code. As written, the result of the call fun(new A())
is a Function1[Unit, Unit]
. You'd have to apply
that function to get the println
invoked
// Exiting paste mode, now interpreting.
defined class A
defined module Main
scala> Main.main(Array())
scala> def doIt { val fun = (_: A).m _; fun(new A())() }
doIt: Unit
scala> doIt
m()
Upvotes: 1