There is Either
in scala which allow a variable to have 2 types value.
val x: Either[String, Int] = Left(\"apple\")
However, I
IMO the most natural way to express this is to create an ADT (Algebraic Data Type):
sealed trait Foo
final case class Bar(s: String) extends Foo
final case class Baz(i: Int) extends Foo
final case class Fizz(d: Double) extends Foo
final case class Buzz(l: List[String]) extends Foo
And now you can pattern match on Foo
:
val f: Foo = ???
f match {
case Bar(s) => // String
case Baz(i) => // Int
case Fizz(d) => // Double
case Buzz(l) => // List[String]
}