Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern for mapping with identity and applying a side-effect

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?

like image 997
Mario Galic Avatar asked Mar 12 '26 10:03

Mario Galic


1 Answers

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)
like image 96
Dima Avatar answered Mar 14 '26 02:03

Dima