How to match Enumerations in Scala?

Viewed 50

I have multiple enum objects as follows (these are just examples):

object Status extends Enumeration {
  val Pending, Done = Value
}

object Gender extends Enumeration {
  val Female, Male, Other = Value
}

...

And, I want to match any object extending Enumeration. This one works:

def func(anyVal: Any): String = anyVal match {
  case strVal: String             => "This is a String"
  case status: Status.Value       => "This is an Enumeration"
  case gender: Gender.Value       => "This is an Enumeration"
  ...
}

However, I don't need to match enums separately. Something like this would be great:

def func(anyVal: Any): String = anyVal match {
  case strVal: String             => "This is a String"
  case e: Enumeration.Value       => "This is an Enumeration"
}

But, this doesn't work. Do you have any idea?

1 Answers

Try with type projection Enumeration#Value

anyVal match {
  case strVal: String       => "This is a String"
  case e: Enumeration#Value => "This is an Enumeration"
}

instead of Enumeration.Value. Note Value class is a member of Enumeration class

abstract class Enumeration { 
  ...
  abstract class Value { 
      ...
  }
}

so we need type projection to refer to its type.

As a side note, dot notation can only be used if the left-hand side is a value. Also if possible try to avoid Any in the design, as in a sense it defeats the strengths of using Scala which is rich type information.

Related