0

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..

jcm
  • 5,499
  • 11
  • 49
  • 78
  • I find this answer by @Daniel C. Sobral as the best explanation till date: http://stackoverflow.com/questions/4543228/whats-the-difference-between-and-unit/4545703#4545703 – Sudheer Aedama Jul 23 '14 at 04:42

2 Answers2

2

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]].

dhg
  • 52,383
  • 8
  • 123
  • 144
0

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(_())
Xiaohe Dong
  • 4,953
  • 6
  • 24
  • 53