Scala variable with multiple types

前端 未结 3 518
遇见更好的自我
遇见更好的自我 2021-01-02 11:22

There is Either in scala which allow a variable to have 2 types value.

val x: Either[String, Int] = Left(\"apple\")

However, I

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-02 11:52

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

提交回复
热议问题