Skip to content

Instantly share code, notes, and snippets.

@JoolsF
Created September 29, 2018 17:21
Show Gist options
  • Select an option

  • Save JoolsF/491e6e31d8bc179e8bea611a30e98411 to your computer and use it in GitHub Desktop.

Select an option

Save JoolsF/491e6e31d8bc179e8bea611a30e98411 to your computer and use it in GitHub Desktop.
Cats either asRight
case class Error(e: String)
/**
* These “smart constructors” have advantages over Left.apply and Right.apply
* because they return results of type Either instead of Left and Right.
* This helps avoid type inference bugs caused by over-narrowing
*/
def sumPositive(l: List[Int]): Either[Error, Int] = {
l.foldLeft(0.asRight[Error]) { (acc: Either[Error, Int], i: Int) =>
if (i > 0) {
acc.map(_ + i)
} else {
Left(Error(s"negative value in list $i"))
}
}
}
sumPositive(List(1, 2, 3, -1, 4)) // Left(Error(negative value in list -1))
sumPositive(List(1, 2, 3, 4)) // Right(10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment