Scala变量有多种类型

Ra *_* Ka 6 scala

Either在阶其允许变量具有2种值.

val x: Either[String, Int] = Left("apple")
Run Code Online (Sandbox Code Playgroud)

但是,我希望变量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.
Run Code Online (Sandbox Code Playgroud)

有没有办法实现这个目标?

Yuv*_*kov 19

IMO最自然的表达方式是创建一个ADT(代数数据类型):

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
Run Code Online (Sandbox Code Playgroud)

现在你可以模式匹配Foo:

val f: Foo = ???
f match {
  case Bar(s) => // String
  case Baz(i) => // Int
  case Fizz(d) => // Double
  case Buzz(l) => // List[String]
}
Run Code Online (Sandbox Code Playgroud)


Arn*_*-Oz 10

看看没有形状的副产品

"shapeless有一个Coproduct类型,Scala的概括为任意数量的选择"