Scala variable with multiple types

前端 未结 3 519
遇见更好的自我
遇见更好的自我 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]
    }
    
    0 讨论(0)
  • 2021-01-02 11:55

    Look at shapeless coproducts

    "shapeless has a Coproduct type, a generalization of Scala's Either to an arbitrary number of choices"

    0 讨论(0)
  • 2021-01-02 12:02

    Not sure what your exact use case is but check this out: scala type alias - how to have a type that represent multiple data types

    Basically you create a trait represents an umbrella/parent class. Then you define multiple classes that extend the parent trait and put the parent trait as the expected parameter type in your function. Then you can pass any type that extends that parent trait.

    You have to wrap the subtypes, but this allows you to have one type that represents multiple types.

    Another way could be to use generic types and type bounds. These articles talk about these two subjects:

    • http://docs.scala-lang.org/tutorials/tour/variances.html
    • How do I setup multiple type bounds in Scala?

    I'm still learning Scala, but hope this helps! :)

    0 讨论(0)
提交回复
热议问题