https://kotlinlang.org logo
#arrow
Title
# arrow
m

Marc Plano-Lesay

01/26/2023, 9:57 PM
Hello! I'm updating from Arrow 1.1.3 to 1.1.5, and migrating the deprecations in the Either API. While most of them make sense and have very clear/simple replacements, I find
filterOrElse
to be a bit annoying - while implementing something similar with
flatMap
is easy enough, it loses quite a lot in terms of readability. 🧵
solved 1
Here's what I used to have:
Copy code
.filterOrElse {
        predicate = { userAccountManager.hasSession(it) },
        default = { SignInError.Internal },
      }
And with `flatMap`:
Copy code
.flatMap {
        if (userAccountManager.hasSession(it)) {
          Right(it)
        } else {
          Left(SignInError.Internal)
        }
      }
Previously, the intention was obvious just by reading the
filterOrElse
name - which is not the case at all anymore. Is there a more expressive way to replace
filterOrElse
that I'm missing?
s

Stylianos Gakis

01/27/2023, 12:48 AM
Filter makes me think of lists tbh. filterOrElse doesn’t sound intuitive at all not gonna lie 😄 As someone who hadn’t seen this function before, I’d much prefer to see
Copy code
.flatMap {
  if (userAccountManager.hasSession(it)) {
    it.right()
  } else {
    SignInError.Internal.left()
  }
}
In fact, I’d personally rather see something like this instead
Copy code
val x = either<SignInError, Session?> {
  val session: Session = Session // you had this before the flatMap, might need to `bind()` here
  ensure(userAccountManager.hasSession(session)) { SignInError.Internal }
  session
}
m

Marc Plano-Lesay

01/27/2023, 12:54 AM
I guess this
either
block +
ensure
might be the better option indeed. Thanks, I hadn't considered that one!
s

Stylianos Gakis

01/27/2023, 12:56 AM
Yeah do give it a try and tell us how it went for you. I personally find myself opting for that style more often than not lately.
m

Marc Plano-Lesay

01/27/2023, 12:57 AM
I quite like the flowable style of chaining calls, but it does indeed require knowing the API inside and out where a more imperative style is usually clear to anyone
9 Views