Skip to content

Instantly share code, notes, and snippets.

@Mahoney
Created July 18, 2019 18:21
Show Gist options
  • Select an option

  • Save Mahoney/2580e27ea3f1f475342f3f764000613d to your computer and use it in GitHub Desktop.

Select an option

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
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