Scala method types and methods as parameters

前端 未结 3 1786
我在风中等你
我在风中等你 2021-01-18 10:26

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

3条回答
  •  一生所求
    2021-01-18 10:50

    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?

提交回复
热议问题