In the following code example, I do not understand why the function fun can be passed as an argument to the method addAction
. The method fun
is of
Take this as an introductory example:
def fun() { println("fun1 executed.") }
val a1 = fun
val a2: () => Unit = fun
Both lines compile and (thanks to type inference) they look equivalent. However a1
is of type Unit
while a2
is of type () => Unit
... How is this possible?
Since you are not explicitly providing type of a1
, compilers interprets fun
as a method fun
call of type Unit
, hence the type of a1
is the same as type of fun
. It also means that this line will print fun1 executed.
However, a2
has explicitly declared type of () => Unit
. The compiler helps you here and it understands that since the context requires a function of type () => Unit
and you provided a method matching this type, it shouldn't call that method, but treat it as first class function!
You are not doomed to specify type of a1
explicitly. Saying:
val a1 = fun _
Do you now understand where your problem is?