I'm currently learning Scala by working through the "Programming in Scala" book. So far, there have been nice explanations for everything that looks weird (from a Java programmer's perspective), but this one example using a Stream to generate the Fibonacci sequence leaves me kind of puzzled:
def fibFrom(a: Int, b: Int): Stream[Int] =
a #:: fibFrom(b, a + b)
How is the construction of the Stream done? Of course the #::
operator is somehow responsible for that. I understand that since it ends in :
, it is right-associative, but that does not explain the creation of the Stream. I guess it is implicitly translated to a constructor somehow but I don't see why and how exactly.
I've already looked for answers in Predef.scala
and LowPriorityImplicits.scala
but no luck so far.
Can anyone enlighten me?
It is right associative so it works as a method on the right argument:
fibFrom(b, a + b).#::(a)
At least that is what it tries to do syntactically. Stream[Int]
does not have such a method. Luckily though, object Stream
has an implicit to some class ConsWrapper
which has this method (code).
So, what you get after implicit resolution is this:
immutable.this.Stream.consWrapper(fibFrom(b, a + b)).#::(a)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With