Why does Scala apply thunks automatically, sometimes?

前端 未结 4 686
花落未央
花落未央 2021-02-05 03:39

At just after 2:40 in ShadowofCatron\'s Scala Tutorial 3 video, it\'s pointed out that the parentheses following the name of a thunk are optional. \"B

4条回答
  •  别那么骄傲
    2021-02-05 04:34

    The problem is here:

    Buh?" said my functional programming brain, since the value of a function and the value it evaluates to when applied are completely different things.

    Yes, but you did not declare any function.

    def f(): Int = { counter = counter + 1; counter }
    

    You declared a method called f which has one empty parameter list, and returns Int. A method is not a function -- it does not have a value. Never, ever. The best you can do is get a Method instance through reflection, which is not really the same thing at all.

    val b = f _     // Hey Scala, I mean f, not f()
    

    So, what does f _ means? If f was a function, it would mean the function itself, granted, but this is not the case here. What it really means is this:

    val b = () => f()
    

    In other words, f _ is a closure over a method call. And closures are implemented through functions.

    Finally, why are empty parameter lists optional in Scala? Because while Scala allows declarations such as def f = 5, Java does not. All methods in Java require at least an empty parameter list. And there are many such methods which, in Scala style, would not have any parameters (for example, length and size). So, to make the code look more uniform with regards to empty parameter list, Scala makes them optional.

提交回复
热议问题