Why future has side effects?

前端 未结 4 460
太阳男子
太阳男子 2020-12-16 18:13

I am reading the book FPiS and on the page 107 the author says:

We should note that Future doesn’t have a purely functional interface. This is part

4条回答
  •  孤城傲影
    2020-12-16 18:24

    As far as I know, Future runs its computation automatically when it's created. Even if it lacks side-effects in its nested computation, it still breaks flatMap composition rule, because it changes state over time:

    someFuture.flatMap(Future(_)) == someFuture // can be false
    

    Equality implementation questions aside, we can have a race condition here: new Future immediately runs for a tiny fraction of time, and its isCompleted can differ from someFuture if it is already done.

    In order to be pure w.r.t. effect it represents, Future should defer its computation and run it only when explicitly asked for it, like in the case of Par (or scalaz's Task).

提交回复
热议问题