2

I'm working with Java Immutable library http://immutables.github.io/ I have 3 Immutable classes, so basically 3 classes with a bunch of params. For each of these classes, we have a unique key.

So, I decided to define an interface like this:

public interface DataKey<T> {
    public T getKey();
}

Now, I want each Immutable class to implement this Interface, here is an example

@Value.Immutable
public abstract class CurrencyDemo implements DataKey<String> {
    public abstract String getCode();

    @Value.Derived
    public String getKey() {
        return getCode();
    }

}

This works all fine. I was able to get this working because I knew that I should provide an implementation for getKey, otherwise I'll get an Exception when building the Immutable java object.

Is there any way to oblige the user to force the Developer to provide an implementation of getKey() when they define an immutable class implementing the DataKey interface??

Purpose; I could write common code on these immutable classes with a guarantee that they will all have a method called getKey()

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
Nitesh
  • 193
  • 1
  • 2
  • 17
  • When a developer defines a class that implements DataKey, whether or not that class is `Immutable`, they _are_ obliged to provide an implementation of `getKey()` (or mark their class as abstract) — that's how implementing an interface works, so I'm not sure what you are asking. Maybe I'm just interpreting the question wrong(?) – Stephen P Aug 28 '19 at 21:01
  • Abstract class(CurrencyDemo here) will not force the developer to implement a method from the Interface(DataKey). If you want to force the developer to provide an implementation for getKey() in CurrencyDemo, then remove the abstract keyword from the CurrencyDemo. In this case anyways we cannot create an object of CurrencyDemo, since it is abstract, and any subclass (which again is not abstract) should be providing an implementation of the said method or the compiler will complain. Hope this helps ! – MRTJ Aug 28 '19 at 21:40
  • Immutable classes are by definition defined as Abstract. Immutable library generates the implementation of this class. Implementation generated by the Immutable will have the implementation of getKey(). But that does not work for me. I want the users to provide a custom implementation of getKey() like in the example I mentioned – Nitesh Aug 29 '19 at 06:57

0 Answers0