Is there a clearer way of expressing the following pattern:
def getUser(id: String): Option[User] = ???
getUser("12345").map { user =>
someSideEffect(user)
user
}
Note how given a functor we map with the identity function but also apply the side-effecting function to the boxed value.
Future.andThen does exactly this:
Applies the side-effecting function to the result of this future, and returns a new future with the result of this future.
Is there something like Future.andThen but in the general case for any functor?
There isn't anything out of the box. People often add it with something like this:
object ImplicitUtils {
implicit class Utils[T](val t: T) extends AnyVal {
def tap(f: T => Unit): T = { f(t) ; t }
}
}
So that, now you can write:
import ImplicitUtils._
val user = getUser("foo").tap(someSideEffect)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With