How to combine option with Kleisli

157 Views Asked by At

Given a method

def f[A, B, C](a: A) : Kleisli[Future, B, C] = ???

I need a combinator working with an Option[A]

My first try was :

def g[A, B, C](a: Option[A], default: => C) = a match {
  case Some(a) => save(a)
  case None => Kleisli[Future, B, C] { _ => Future.successful(default) }
}

But after reading How to combine sequence of Kleisli, I came up with a better version :

def g[A, B, C](a: Option[A], default: => C) : Kleisli[Future, B, C] = 
  a.traverseU(f[A, B, C]).map(_.getOrElse(default))

Any idea to improve ?

1

There are 1 best solutions below

0
On BEST ANSWER

Here is the implementation of the idea suggested in comment by @TravisBrown.

def g[A, B, C](a: Option[A], default: => C) : Kleisli[Future, B, C] =
  a.fold(Future(default).liftKleisli[B])(f)

Readability is maybe better.