lazy function definitions in scala

后端 未结 6 1604
滥情空心
滥情空心 2021-02-02 16:49

I\'ve been learning scala and I gotta say that it\'s a really cool language. I especially like its pattern matching capabilities and function literals but I come from a javascri

6条回答
  •  半阙折子戏
    2021-02-02 17:23

    Scala has lazy vals, whose initializers are not evaluated unless and until the val is used. Lazy vals may be used as method local variables.

    Scala also has by-name method parameters, whose actual parameter expressions are wrapped in a thunk and that thunk is evaluated every time the formal parameter is referenced in the method body.

    Together these can be used to achieve lazy evaluation semantics such as are the default in Haskell (at least in my very limited understanding of Haskell).

    def meth(i: => Int): Something = {
      //        ^^^^^^ by-name parameter syntax
      lazy val ii = i
      // Rest of method uses ii, not i
    }
    

    In this method, the expression used as the actual parameter will be evaluated either zero times (if the dynamic execution path of the method body never uses ii) or once (if it uses ii one or more times).

提交回复
热议问题