Reputation: 5659
Could someone please explain this piece of code:
val ns: Iterator[Int] = (1 to 3).iterator
ns.map(_ => () => block)
where
block: => Future[T]
Basically I'm just confused about what's going on with the _
, =>
, and Unit ()
syntax. The way I am trying to read it is 'we map a function which returns a function that takes no params and returns a Future[T] over the list of integers'. Is this correct? I'm always confused when I see multiple =>
operators in a row..
Upvotes: 0
Views: 117
Reputation: 5023
I think this block: => Future[T] maybe the signature of the method. It means call-by-name. Basically, you can understand that it is just a type Future[T] which is lazy evaluated but not a function
val ns: Iterator[Int] = (1 to 3).iterator
ns.map(_ => () => block)
This will return Iterator[() => Future], so yes, you are right, this transform to a function which takes nothing to Future. The good thing of this is that it will not evaluate the Future immediately, it will be called when you invoked.
val result = ns.map(_ => () => block)
result.foreach(_())
Upvotes: 0
Reputation: 52691
Yes, you are correct.
It's parsed like this:
ns.map(_ => (() => block))
And the () => ?
syntax is just defining a parameterless function:
val f = () => 1
f() // 1
So the integer in ns
is ignored, and you just get an iterator of functions that take no parameters and return Futures: Iterator[() => Future[T]]
.
Upvotes: 2