Scala method types and methods as parameters

前端 未结 3 1744
我在风中等你
我在风中等你 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 11:03

    You need to write fun _ in the first case to avoid calling the method and performing eta-expansion instead.

    This will work:

    actions = (fun _) :: actions
    

    If you don't do this, then fun is evaluated.

    For more details, see Section 6.7 (Method Values) of the Scala Language Reference.

    As to why fun is not evaluated in the second case, it is because type inference can clearly conclude that addAction expects a function. By the way, the type of fun is technically ()Unit, not Unit, that is, a method type, and not a value type. See Section 3.3.1 in the reference for more.

提交回复
热议问题