Scala variable with several types

There are scala's Eitherthat allow a variable to have a value of type 2.

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

However, I want to have more than two types for the variable x, for example. {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?

+6
source share
3 answers

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 map the pattern to Foo:

val f: Foo = ???
f match {
  case Bar(s) => // String
  case Baz(i) => // Int
  case Fizz(d) => // Double
  case Buzz(l) => // List[String]
}
+18
source

Look at shapeless coproducts

"formless is of type Coproduct, generalization of Scala Or in an arbitrary number of options"

+10
source

, , : scala - ,

, / . , . , .

, , .

. :

I am still participating in Scala, but hope this helps! :)

+4
source

Source: https://habr.com/ru/post/1675165/


All Articles