Scala变量有多种类型(Scala variable with multiple types)

编程入门 行业动态 更新时间:2024-10-28 04:24:51
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 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] }

更多推荐

本文发布于:2023-08-04 10:25:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1414913.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   有多种   类型   Scala   multiple

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!