Future.onSuccess versus Future.map

784 views
Skip to first unread message

Oliver Ruebenacker

unread,
Oct 10, 2014, 1:06:49 PM10/10/14
to scala...@googlegroups.com

     Hello,

  Suppose I have:

  val fut: Future[A] = { ...}
  val f: A => B = { ... }

  Can I always replace this:

  fut.onSuccess { case a: A => f(a) }

  by this?

  fut.map(f(a))

  Thanks!

     Best, Oliver

Joheinz

unread,
Oct 10, 2014, 2:57:31 PM10/10/14
to Oliver Ruebenacker, scala-user

No. unless you are not interested in B and f is full of side effects as on success returns unit and map a Future[B].

Markus

--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

√iktor Ҡlang

unread,
Oct 11, 2014, 4:56:10 AM10/11/14
to Oliver Ruebenacker, scala-user
Hi Oliver,

`onSuccess` is just an alias for `foreach` to harmonize with `onFailure`. (Both onSuccess and onFailure is scheduled to be deprecated for 2.12 because they are redundant due to `foreach` and `failed.foreach`)

So the question then becomes: Can I always replace `foreach` with `map`?

Interesting!

Well there are a couple of different things to consider:

1) `map` returns the result of the application of the function passed in as a new `Future` and `foreach` returns `Unit`.
2) Since `foreach` does not return anything—any thrown exceptions will be "invisible" to the caller, since they are executed asynchronously, which means that they will be passed to the `ExecutionContext`s `reportfailure`-method whereas with `map` the returned `Future` will contain any non fatal exceptions thrown by the application of the function passed in.


--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Cheers,
Reply all
Reply to author
Forward
0 new messages