a.moussa a.moussa - 2 months ago 12
Scala Question

How can I test if a Java object is an enum in scala?

I have a method which converts a string to an int and a Java enum to an int. For other data types, it doesn't do any conversion.

def myConverter[T](attributeValue: T) = {
if (attributeValue.isInstanceOf[String]) {
attributeValue.asInstanceOf[String].toInt
} else if (attributeValue.isInstanceOf[Enumeration$Value]) {
CodeReferenceEx.toInteger(attributeValue.asInstanceOf[Enumeration$Value])
} else {
attributeValue
}
}


The method never enters the
elseif
block (
Enumeration$Value
) because the condition is always evaluated to false. I am using a java enumeration object.

Does anyone have any idea? Thanks

Answer Source

Given a Java enum:

public enum C {
    ONE, TWO
}        

And a Scala enum:

object E extends Enumeration {
  val A = Value
}

The following works for both:

def myConverter[T](attributeValue: T) = {
  attributeValue match {
    case str: String =>
      str.toInt
    case _: Enumeration =>
      println("Scala Enum!")
    case _: Enumeration#Value =>
      println("Scala Enumeration Value!")
    case _ if attributeValue.getClass.isEnum =>
      println("Java Enum!")
    case _ => println("oops")
  }
}

def main(args: Array[String]): Unit = {
  myConverter(E)
  myConverter(E.A)
  myConverter(C.ONE)
}

Yields:

Scala Enum!
Scala Enumeration Value!
Java Enum!