Chris 0_ö
Chris 0_ö

Reputation: 3

How can I change, replace or expand a 3rd-party Enum (Java) in Scala?

I have a Scala-Project that uses a Service-Factory (3rd-Party Java) and a Configuration-Enum (3rd-Party Java).

I need to call the Factory with my own configuration values (not represented in the existing Configuration-Enum).

How can a handle this problem? I have no experience with Scala but some with Java. Can I use Reflection or something else?

Configuration-Enum (3rd-Party Java):

public enum Config {
  ENV1("host-x"),
  ENV2("host-y");
  
  private final String url;

  Config (String url) {
    this.url = url;
  }

  public String getUrl() {
    return url;
  }
}

Service-Factory (3rd-Party Java):

public class Factory {

  private final Service service;

  public Factory(Config config) {
     this.service = initService(config.getUrl()); // the problematic line...
  }

  public Service getService() {
    return service;
  }
}

My Scala-Project:

def doSomting: Unit = {
  val aConfig: Config = Config.valueOf("ENV1")
  new Factory(aConfig).getService().start() // uses host-x from the enum ENV1
  // How can I pass my own host (host-z) into the Factory?
}

Upvotes: 0

Views: 116

Answers (1)

Mateusz Kubuszok
Mateusz Kubuszok

Reputation: 27595

You cannot create a new value to existing enum. But you can create a new type which is a superset of old enum and your extensions.

If you have the control over the call site, you could introduce some extensions like: Either[OriginalEnum, ExtensionsEnum] where you could make distinction between one set of values and the other and e.g. pass original ones where of you have extension, your could provide a separate behavior:

type ExtendedEnum = Either[OriginalEnum, ExtensionEnum]

def expectingOriginal(value: OriginalEnum) Something = ...

def extendedEnum(value: ExtendedEnum) = value match {
  case Left(original)  => expectingOriginal(original)
  case Right(extended) => // special handling extending original behavior
}

If you cannot do it... well, then you have no option. Enums were designed in such a way that there is a fixed number of them both in compile and runtime, so e.g. checking if something is an enum of some value is often done by reference comparison. So if you add a new value through some, I don't know, illegal binary manipulations then all the code that used to do exhaustive checks would now have unhandled cases. That's why the compiler will prevent you from doing so.

Upvotes: 1

Related Questions