Use of Scala by-name parameters

后端 未结 4 1899
臣服心动
臣服心动 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:11

    In def cons[A](hd: => A, tl: => Stream[A]) : Stream[A]

    the type of hd is A, tl is Stream[A]

    whereas in case class Cons[+A](h: () => A, t: () => Stream[A]) extends Stream[A]

    h is of type Function0[A] and t of type Function0[Stream[A]]

    given the type of hd is A, the smart constructor invokes the case class as

     lazy val head = hd
     lazy val tail = tl
     Cons(() => head, () => tail) //it creates a function closure so that head is accessible within Cons for lazy evaluation
    

提交回复
热议问题