Use of Scala by-name parameters

后端 未结 4 1905
臣服心动
臣服心动 2020-12-20 22:43

I am going through the book \"Functional Programming in Scala\" and have run across an example that I don\'t fully understand.

In the chapter on strictness/laziness

4条回答
  •  别那么骄傲
    2020-12-20 23:00

    Note that the parameters of the method cons are by-name parameters (hd and tl). That means that if you call cons, the arguments will not be evaluated before you call cons; they will be evaluated later, at the moment you use them inside cons.

    Note that the Cons constructor takes two functions of type Unit => A, but not as by-name parameters. So these will be evaluated before you call the constructor.

    If you do Cons(head, tail) then head and tail will be evaluated, which means hd and tl will be evaluated.

    But the whole point here was to avoid calling hd and tl until necessary (when someone accesses h or t in the Cons object). So, you pass two anonymous functions to the Cons constructor; these functions will not be called until someone accesses h or t.

提交回复
热议问题