Confusion re: solving the finnancy number with Scala infinite streams that used the def'd method within def

I studied some posts in scala infinite streams to better wrap my lead this concept. I liked the simple solution in this post , which I 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 happening is that we are returning a Stream [Long] object with a tail method. To test this (seemingly incorrect) hypothesis, I did the following, which will 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 seems to be based on redefinition. So now I'm wondering what exactly happens with scala constructs that have def of some type 'T', where the value of this block contains another def, which, at first glance, overrides the T method?

Thank you in advance for your enlightenment!

EDIT is the result of a survey of the solution in an 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}") } 
+4
source share
1 answer

To override the X method, you first need to create a class that extends already has some other class that contains the X method. In your example, you are not really creating a new class anywhere! Here you just created a nested function inside another function, which, unfortunately, is called tail (therefore it has the same name as one of the functions inside Stream ).

Thus, basically the fib method returns an instance of Stream , which is recursively created by your nested tail function. To create an actual Stream instance, this method uses the #:: operator. You are not creating a new class, just a new instance.

doc explains well what #:: does.

Try changing the name from tail to myTail (or any other name that is not part of Stream ) and you will see that it still works.

What is the reason for using this construct: one common reason is the structuring of your code, you may notice that you cannot use this tail function outside its external method.

+4
source

All Articles