Why does Scala apply thunks automatically, sometimes?

前端 未结 4 685
花落未央
花落未央 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:29

    In your example

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

    is defining a method, not a function. AFAIK methods are promoted to functions automatically in Scala depending on context. To define a function you can write

    val f = () => { counter = counter + 1; counter }
    

    and I think you will get what you want.

提交回复
热议问题