Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Enumeration Data As String?

Tags:

scala

Is possible that an enumeration data type in Scala can be implemented as String as

enum Currency {CAD, EUR, USD }

in Java instead of

object Currency extends Enumeration {

  val CAD, EUR, USD = Value
}

which data value is binary?

I write a same functionality in both Java and Scala. The enumeration data is saved into database. The Java version works nicely with String value, but not the Scala version which is binary data.

like image 279
vic Avatar asked Jul 16 '26 11:07

vic


2 Answers

You can do:

object Currency extends Enumeration {
  type Currency = String
  val CAD = "CAD"
  val EUR = "EUR"
  val USD = "USD"
}

And then the underlying type of each is an actual String.

like image 169
Yuval Itzchakov Avatar answered Jul 19 '26 01:07

Yuval Itzchakov


You can try using toString.

Currency.Cad.toString() == "Cad"
Currency.withName("Cad") == Currency.Cad

Also if you want a readable format of your choice you can choose your string

object Currency extends Enumeration {
    val CAD = Value("Canadian Dollar")
    val EUR, USD = Value
}

See this blog post for full info.

like image 33
Eytan Avatar answered Jul 19 '26 02:07

Eytan