Fuzzy Notation in Scala Code Snippet

I am taking the Reactive Programming Principles course in Curser and have noticed a few times a notation that I cannot fully understand. So I hope you can help me understand. Here's a snippet of code:

def retry(noTimes:Int)(block: => Future[T]): Future[T] = {
 val ns: Iterator[Int] = (1 to noTimes).iterator
 val attempts: Iterator[Future[T]] = ns.map(_ => () => block)
 val failed = Future.failed(new Exception)
 attempts.foldLeft(failed) ((a, block) => a recoverWith {block()})
}

      

It is not clear to me why attempts

it is not easy to define the value ns.map(_ => block)

? The type of the value attempts

is Iterator[Future[T]]

and map

as it seems to me it should express Iterator[() => Future[T]]

. Could you figure it out?

+3


source to share


1 answer


With this:
ns.map(_ => block)

Block

will execute directly, this is not what the author would like.
Similar to the Call-By-Value parameter .

However, with this : ns.map(_ => () => block)

, it is similar to the Call-By-Name parameter , which means the block code will only be executed when explicitly called in the base function.

If I remember correctly, the author of the course said something like:
"Sit down, have a coffee and deeply analyze the function to understand why we need to execute the code block

lazily";)

UPDATE -------



In the signature, the wrapping method is block

declared as a parameter to be called by name:

block: => Future[T]

      

Therefore, the best fit Future[T]

matches () => block

, explains why:

val attempts: Iterator[Future[T]]

not val attempts: Iterator[() => Future[T]]

+2


source







All Articles