具有多种类型的Scala变量 [英] Scala variable with multiple types

查看:45
本文介绍了具有多种类型的Scala变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

scala 中有 Either 允许一个变量有两种类型的值.

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

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

但是,我希望变量 x 有超过 2 种类型,例如{String, Int, Double, List[String] }.

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(代数数据类型):

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

现在你可以对 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]
}

这篇关于具有多种类型的Scala变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆