Search code examples
javareflectionimmutabilityimmutables-library

Immutables custom create and of methods


I am changing a library that uses Immutables. In the class that I change I just added a new variable and in the generated classes I see different signatures in the create and of methods.

ImmutableMyClass.of(previous variables ...,  int varNew)

ModifiableMyClass.create(previous variables ...,  int varNew)

Since there are users of this library that call the previous versions of these methods I need to keep previous versions while providing the new versions for a new feature; otherwise, apparently, I am breaking the backward compatibility.

How do I have Immutables create custom create and of methods?


Solution

  • You just add the missing methods yourself as defined in library documentation here : https://immutables.github.io/immutable.html#expressive-factory-methods. So for the missing methods you define public static MyClass of(...) and public static MyClass create(...) methods as below

    @Value.Modifiable
    @Value.Immutable
    public abstract class Point {
      @Value.Parameter
      public abstract double x();
      @Value.Parameter
      public abstract double y();
      //You added this for example
      @Value.Parameter
      public abstract double z();
    
      public static Point origin() {
        return ImmutablePoint.of(0, 0);
      }
    
      public static MyClass of(double x, double y) {
        return ImmutableMyClass.of(x, y, 0); // or another implementation you need
        
      }
    
       public static MyClass create(double x, double y) {
        return ModifiableMyClass.create(x, y, 0); // or another implementation you need
      }
    }