konquestor
konquestor

Reputation: 1308

Enforce values a class member can be assigned : Scala

I intend to restrict the values the string member of my class can take. For eg: for a member named country, only allowable values should be the countries that i have defined like 'US', UK, CN, etc. This constants need to be string constants.

I thought of using Enum, but that does not give me flexibility with the String constants. Or may be i am not aware of how to use it.

Any suggestions?

Upvotes: 1

Views: 84

Answers (3)

nmat
nmat

Reputation: 7591

What is the problem with the enum? Seems like a good fit for what you need. Here is an example:

object Country extends Enumeration {
  val US = Value("United States")
  val UK = Value("United Kingdom")
}

case class MemberCountry(country: Country.Value)

//example instantiation
MemberCountry(Country.UK)
MemberCountry(Country.withName("United States"))

Upvotes: 2

Vikas Bhardwaj
Vikas Bhardwaj

Reputation: 1

Enumeration has its strengths and weaknesses in Scala. You could use any approach highlighted above namely:

  • Enumeration subclass
  • Use Sealed Trait/Class.

Both approaches have benefits and potential tradeoffs. It might be worth reading through this informative article on this issue: http://underscore.io/blog/posts/2014/09/03/enumerations.html

Upvotes: 0

Aivean
Aivean

Reputation: 10882

Enum support is not that good in Scala. First, scala's built-in Enumeration is crap, don't use it.

The common approach for enumerations is sealed trait/class:

sealed abstract class Country(val name:String)

object Country {
  case object US extends Country("US")
  case object UK extends Country("UK")
  case object CN extends Country("CN")

  val values = Set(US, UK, CN)
}

Country.values.find(_.name == "US")

It has one problem, if you want the list of all possible values, you need to enumerate them yourself (the values field in the example above).

However, there are alternatives that solve that problem. You can go with macro (check this thread).

Or use third-party library.

Upvotes: 1

Related Questions