My workplace has been experimenting in moving from Java to Scala for some tasks, and it works well for what we’re doing. However, some preexisting logging methods expect a java.lang.Enum
. The logging method is defined in the (Java) base class, and the subclasses can define their own enums, which the logger will track across all instances in multiple threads/machines.
It works like this in Java:
public class JavaSubClass extends JavaBaseClass {
enum Counters {
BAD_THING,
GOOD_THING
}
public void someDistributedTask() {
// some work here
if(terribleThing) {
loggingMethod(Counters.BAD_THING)
} else {
loggingMethod(Counters.GOOD_THING)
// more work here
}
}
}
Then, when the task has finished, we can see that
BAD_THING: 230
GOOD_THING: 10345
Is there any way to replicate this in Scala, either by creating Java Enum
s or converting from Enumeration
to Enum
? I have tried extending Enum
directly, but it seems to be sealed, as I get the error in the console:
error: constructor Enum in class Enum cannot be accessed in object $iw
Access to protected constructor Enum not permitted because
enclosing object $iw is not a subclass of
class Enum in package lang where target is defined
Advertisement
Answer
If you need a java enumeration, then you need to write it in Java. There are things you can do in Scala to replace the use cases of Enum
, but there’s nothing in Scala that replicates the Java mechanics of Enum
.