scala-library-next icon indicating copy to clipboard operation
scala-library-next copied to clipboard

TapEach For Futures and Try

Open sinanspd opened this issue 4 years ago • 3 comments

Reviving this old idea that we closed under scala/scala-dev#661.

Motivation

  1. Currently andThen defined for Futures, doesn't preserve the error behavior. We could argue that if the side-effecting code throws an error, the Future is ought to fail, as @NthPortal previously pointed out, preserving the behavior in Iterator and LazyList

  2. More consistent interface for all Monadic Product types (Option, List, all other Iterables etc.). If you want to do something like

Future|Option|Try .log(s"logging the value $_").map(...).log(...)

You either need to put F|O|T.map(r => { log(....) r}) every where, which is rather ugly,

Or you need to define extension methods on all them

implicit class MonadicLog[+B <: Product, A] (val u: B){
  def log(l: String): B = {
      log(l)
      u
    }  
 }

implicit class FutureLog[T, A](val u: Future[T]){
    def log(l: String) : Future[T] = {
      println(l)
      u
    }
  }

And so on ....

with a consistent tapEach operation, you can do the following, which is much better IMO

Future.successful(List(Some(1), Some(2), Some(3), Some(4)))
   .tapEach(println)
   .map(_.flatten
        .tapEach(println)
        .filter(_ > 1)
   ).tapEach(println)

I have a draft PR for this, I will push that for everyone to see what this would look like.

Open to comments :)

sinanspd avatar Nov 20 '20 15:11 sinanspd

previous PR was https://github.com/scala/scala/pull/8857

SethTisue avatar Nov 20 '20 15:11 SethTisue

everyone okay with this change? (👍 in favour, 👎 against)

NthPortal avatar Dec 03 '20 04:12 NthPortal

I want to note that if we do this, we should clearly document the difference between this and andThen (perhaps even tweaking the stdlib scaladoc as well?)

NthPortal avatar Dec 03 '20 04:12 NthPortal