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

How test if a Java object is an enum in scala

I have a method wich convert a string to an int and a Java enum to an int. otherwise I don'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
}
}


It never enter to the else if line (Enumeration$Value) because it is always evaluated to false. This is java enumeration object that I use.
do you 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!