Scala变量有多种类型(Scala variable with multiple types)
在scala中有一个允许一个变量有2个类型值的方法。
val x: Either[String, Int] = Left("apple")但是,我想为变量x有两种以上的类型,例如{String, Int, Double, List[String] } 。
e.g. val x:[type can be either String, Int, Double or List[String]] //So that I can store either String, Int, Double, List[String] value in x.有什么办法可以做到这一点?
There is Either in scala which allow a variable to have 2 types value.
val x: Either[String, Int] = Left("apple")However, I want to have more than 2 types for variable x e.g. {String, Int, Double, List[String] }.
e.g. val x:[type can be either String, Int, Double or List[String]] //So that I can store either String, Int, Double, List[String] value in x.Is there any way to achieve this?
最满意答案
IMO最自然的表达方式是创建一个ADT(代数数据类型):
sealed trait Foo case class Bar(s: String) extends Foo case class Baz(i: Int) extends Foo case class Fizz(d: Double) extends Foo case class Buzz(l: List[String]) extends Foo现在你可以在Foo上进行模式匹配:
val f: Foo = ??? f match { case Bar(s) => // String case Baz(i) => // Int case Fizz(d) => // Double case Buzz(l) => // List[String] }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 FooAnd 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] }更多推荐
发布评论