Created
July 18, 2019 18:21
-
-
Save Mahoney/2580e27ea3f1f475342f3f764000613d to your computer and use it in GitHub Desktop.
A way to build Eithers as Left or Right specifying the other side's type but with type inference for the value
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
| package scala.util | |
| class RightBuilder[+L] private[util]() { def apply[R](r: R): Right[L, R] = Right(r) } | |
| class LeftBuilder[+R] private[util]() { def apply[L](l: L): Left[L, R] = Left(l) } | |
| object Eithers { | |
| private val leftBuilder = new LeftBuilder[Nothing] | |
| private val rightBuilder = new RightBuilder[Nothing] | |
| def left[R]: LeftBuilder[R] = leftBuilder | |
| def right[L]: RightBuilder[L] = rightBuilder | |
| } | |
| import scala.util.Eithers._ | |
| object Main { | |
| def main(args: Array[String]): Unit = { | |
| val x = right[String](5) | |
| val y = right[Int]("hi") | |
| val x1 = left[Int]("hi") | |
| val y1 = left[String](5) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment