RayRoestenburg / akka-in-action

Accompanying source code for akka in action
https://www.manning.com/books/akka-in-action
MIT License
750 stars 423 forks source link

Chapter up and running: understanding the fold #37

Closed Maatary closed 8 years ago

Maatary commented 8 years ago

In the first chapter up and running i am trying to understand how the fold works but can't figure out:

context.child(name).fold(create())(_ => sender() ! EventExists)

What happen if the child exist, are you still creating a new actor? is the neutral argument lazily evaluated ? why the create is not called in the case the list is not empty ?

RayRoestenburg commented 8 years ago

@Maatary

Option.fold has two argument lists, the first has a call by name (longer explanation here) argument (ifEmpty), the second has a function (f):

final def fold[B](ifEmpty: ⇒ B)(f: (A) ⇒ B): B

The ifEmpty is only evaluated once it is used/referenced inside the implementation of fold, only when the option is empty. If it is not empty, it is not evaluated.

In this case that means that create() is not called if the option is nonEmpty.

Hope that helps.

Maatary commented 8 years ago

Yes it did. I guess my confusion came from, the fact that option.fold is a special case of the fold function. The associative function (2nd parameter) does not take two parameter but one.

Thanks for the tip