I have been studying some posts on scala infinite streams to better wrap my head around this concept. I liked the simple solution in this post, which I have reproduced below:
def fib: Stream[Long] = {
def tail(h: Long, n: Long): Stream[Long] = h #:: tail(n, h + n)
tail(0, 1)
}
My initial understanding of what was going on was that we were returning a Stream[Long] object with the tail method overriden. To test out that (seemingly incorrect) hypothesis, I did the following, which would not compile:
def fib: Stream[Long] = {
override def tail(h: Long, n: Long): Stream[Long] = h #:: tail(n, h + n)
^
|
~error~~~
tail(0, 1)
}
So this solution does seem to be based on an override. So, now I'm wondering.. what exactly is going on with Scala constructs that have a def of some type 'T' where the value of that block contains another def that, on first glance seems to override a method of T ?
Thanks in advance for enlightening me !
EDIT - here is the result of trying out the solution in the excellent answer from Mateusz Dymczyk :
object Foolaround extends App {
def fib: Stream[Long] = {
def pail(h: Long, n: Long): Stream[Long] = h #:: pail(n, h + n)
pail(0, 1)
}
var x = fib.tail.tail.tail.tail.tail.head
println (s"results: ${x}")
}