0
\$\begingroup\$
val y: Seq[Either[String, Int]]

case class Response(value: String)

val notFound = Response("Not Found")
val found    = Response("Found")

val response: Response = y.lastOption
    .map(_.fold(_ => notFound, _ => found))
    .getOrElse(notFound)

I am getting a list of Eithers. I want to get the last Either in the list. I then want to get Rightvalue. If the list is empty or the Either is Left, I want to return a default value. The code does this but can this be done more elegantly and clearer in Scala with perhaps cats? I don't use scalaz.

\$\endgroup\$
1
\$\begingroup\$

Instead of map() - fold() - getOrElse(), you could just use two fold() calls.

val response = Response(y.lastOption
                         .fold("Not Found")(_.fold(_=>"Not Found", _=>"Found")))

Or you could turn it into a single Option with just one fold().

val response = Response(y.lastOption
                         .flatMap(_.toOption)
                         .fold("Not Found")(_ => "Found"))
\$\endgroup\$
  • \$\begingroup\$ Welcome to Code Review. You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. \$\endgroup\$ – Mast Oct 20 '18 at 11:35
1
\$\begingroup\$

Solution without folds, effectively using a filter instead:

l.lastOption.filter(_.isRight).map(_ => found).getOrElse(notFound)

I think it is a bit easier to read because every transformation is a single-function argument (as opposed to fold).

I found that Option.filter is a not-so-often used trick that can save what is effectively a conditional transformation in cases like that.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.