7

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.

3 Answers 3

10

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Extending Enumeration is unnecessary.
Thanks. That works either with or without Enumeration extension.
Is explicitly extending Enumeration bad though? Is it not more clear that it is an enum?
This example code seems to be misleading to me. It creates an empty Enumeration with 3 String constants that cannot be accessed through the values API; they don't have the id property and we can't get/set their order.
6

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.

Comments

0

Alternative solution w/o use of Enumeration:

object Currency {
  val CAD = "CAD"
  val EUR = "EUR"
  val USD = "USD"
}

And then the underlying type of each is an actual String. Usage in the REPL:

scala> val currency = Currency.USD
currency: String = USD

Reasoning: using extends Enumeration and type Currency = String as in the most voted answer apparently have no real benefit and could lead to unexpected results; on the given example, if we called Currency.values we would get an empty set. See the Enumeration API.

See also: https://www.baeldung.com/scala/enumerations

1 Comment

This do not insure exhaustive case matching

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.