Hi
In the previous post, I was trying to understand the ‘next’ method in the Mixin tutorial on scala-lang
Many Scala experts kindly offered their time and effort to helping me understand it.
I proceeded to break my head further. So I went to scastie on my browser and typed in the following code:

Note: The iterator here is a modification of the StringIterator that the tutorial has, but this is so because I am trying to understand stuff.

The RichIterator is the product of one of the kind Scala experts that rewrote the above code for me.

However, I typed in the following code to test all of it:
class IntIter extends BaseIteratorImpl(List(1,2,3,4,5)) with RichIterator

val iter = new IntIter
** iter.foreach(println)**

When I ran it in scastie the output is:

We know what to do next. Create a concrete implementing classThe implementation of the ‘next’ method is naive. It needs to be rewrittenitem returned by iterator is: 11item returned by iterator is: 22item returned by iterator is: 33item returned by iterator is: 44item returned by iterator is: 55

What perplexes me is: why does this work. Let me explain.

so, I invoke: iter.foreach(println)
This causes the foreach method in trait RichIterator to be invoked.
What I do not understand is the syntax of the function parameter of foreach - f: (TypeOfDataHandledByIterator) => Unit)

println is the function passed into the foreach. println is found in the Predef object, and it is the parameterless version

But the signature of the parameter is f: (TypeOfDataHandledByIterator) => Unit)
To me, this means: pass in a function that takes in a type variable and returns a Unit

i tried to change the signature of the foreach method to the following:
def foreach(f: () => Unit): Unit = {

This turned out to be very naive, of course. And for reasons, I do not understand yet.
Scastie failed to compile of course.

I am really intent about getting this right, before moving on to the next chapter in the scala-lang tutorial.

Since foreach accepts a function T => Unit and println is a method, the compiler will basically rewrite iter.foreach(println) to iter.foreach( x => println(x) ). That will work because Predef also has a method def println(x: Any): Unit.