Hey folks, I hope all you guys are doing well !
Recently I came across one weird situation in which I was getting an
Future[Either[String , Future[A]]] and it was getting more and more complex so I thought of taking out the Future from the Either and then flattening it out , as most of us do always 😉
But this time this simple thing was not happening and I was getting frustrated and then while searching for it I came across a very good library for scala known as Cats which seems to solve my problem.
Just FYI, Cats is a library which provides abstractions for functional programming in the Scala programming language. The name is a playful shortening of the word category.
(Copied 😉 from Github )
So this is how I got introduced to Cats !
So how I solved my problem is via writing a function using cats.Functor
For using Cats you need to add the cats dependency in your build.sbt
name := "scala-cats"
version := "0.1"
scalaVersion := "2.12.3"
scalacOptions += "-Ypartial-unification"
libraryDependencies += "org.typelevel" %% "cats-core" % "1.0.0-RC1"
case class A(a:String)
val eitherOfFutures:Either[Future[String], Future[A]]=Right(Future.successful(A("Shiv")))
def eitherFmap[F[_], A, B](either: Either[F[A], F[B]])(implicit F: Functor[F]): F[Either[A, B]] = either.fold(f => F.map(f)(Left(_)), f => F.map(f)(Right(_)))
You can also see it on the sbt Console
So this is how we can convert Either[Future[A],Future[B]] into Future[Either[A,B]].
Method 3: Without Functor’s boilerplate code.
As per comment from M50d pointed out a easier solution :
You can also do it in a more simpler way by using bisequence in cats.instances._ as pointed out by M50d
Recently from the comments from Reddit on this post , I have found a new apporach in simple scala I am adding it here thanks to the user @jangchoe for this code snippet
eitherOfFutures.fold(f => f.map(Left(_)), f => f.map(Right(_)))
If you have any problems look me up on twitter and let me know !
We are also developing a community of developers for bridging the gap between Corporates and the colleges ! If you want to be a part of this movement ! Signup on InternityFoundation
Till then Happy hAKKAing 🙂
- Herding Cats