Skip to content

Instantly share code, notes, and snippets.

@takezoe
Last active January 7, 2017 04:59
Show Gist options
  • Save takezoe/4915a1e25c8e1a5b575e7c5cfe6f0811 to your computer and use it in GitHub Desktop.
Save takezoe/4915a1e25c8e1a5b575e7c5cfe6f0811 to your computer and use it in GitHub Desktop.
sealed trait |[A, B] {
def value: Any
def as[T]: T = value.asInstanceOf[T]
}
object | {
private case class Union[A, B](_1: Option[A], _2: Option[B]) extends |[A, B]{
def value: Any = (_1 match {
case Some(x: |[_, _]) => Some(x.value)
case x => x
}).getOrElse(_2.get)
}
implicit def A_to_Bar2[A, B](a: A): A | B = Union(Some(a), None)
implicit def B_to_Bar2[A, B](a: B): A | B = Union(None, Some(a))
implicit def A_to_Bar3[A, B, C](a: A): A | B | C = Union(Some(a), None)
implicit def B_to_Bar3[A, B, C](a: B): A | B | C = Union(Some(a), None)
implicit def A_to_Bar4[A, B, C, D](a: A): A | B | C | D = Union(Some(a), None)
implicit def B_to_Bar4[A, B, C, D](a: B): A | B | C | D = Union(Some(a), None)
}
import |._
object UnionTypeTest extends App {
def test(arg: String | Int | Boolean): Unit = {
arg.value match {
case x: String => println("String")
case x: Int => println("Int")
case x: Boolean => println("Boolean")
}
}
test("str")
test(123)
test(true)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment