Created
September 29, 2018 17:21
-
-
Save JoolsF/491e6e31d8bc179e8bea611a30e98411 to your computer and use it in GitHub Desktop.
Cats either asRight
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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