# Getting last or return a default value in a Seq[Either[A, B]]

val y: Seq[Either[String, Int]]

case class Response(value: String)

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.

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

val response = Response(y.lastOption


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

val response = Response(y.lastOption
.flatMap(_.toOption)

Solution without folds, effectively using a filter instead:
l.lastOption.filter(_.isRight).map(_ => found).getOrElse(notFound)

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.