0

I'm using the immutables library to create immutable objects from interfaces. However, I can't find a way to make generated classes extend one another in order to make them polymorphic.

Consider this code:

@Value.Immutable
@ImmutableStyle
@JsonSerialize
public interface AbstractAdvert {

    String getAdvertName();

    @Nullable
    String getAdvertRef();

    AdvertPrice getPrice();

    AdvertProvider getProvider();

    @Value.Default
    default Boolean getBillsIncluded() {
        return false;
    }

    @Value.Immutable
    @ImmutableStyle
    @JsonSerialize
    interface AbstractStudioAdvert extends AbstractAdvert {

    }
}

This will generate two classes: Advert and StudioAdvert.

I'd like to have methods elsewhere that take List<Advert> as a parameter but it also accepts List<StudioAdvert> hence I need the polymorphism here.

TLDR: The above code doesn't make generated StudioAdvert extend Advert. I'd like them to have that relationship though.

Any suggestions appreciated.

EDIT 1

In my use case, let's say I have a List<StudioAdvert> and a List<RoomAdvert> that I would like to pass to the same function for processing. The following method does not work at the moment if I use List<Advert> or List<AbstractAdvert> as method's parameter.

public static ProcessedResult processResult(List<AbstractAdvert> adverts) {
    ...
}

The issue is as below. enter image description here

curiousdev
  • 626
  • 8
  • 24
  • 1
    List will work for you. – Prashant Pandey Jul 11 '20 at 10:36
  • Please [edit] your question on how you generate the code and/or how you use the builder/factory classes. – Progman Jul 11 '20 at 10:48
  • Why do you need `StudioAdvert` to extend `Advert`? Both of them extend `AbstractAdvert`, as does `AbstractStudioAdvert`. You can have a `List` and it will accept instances of both generated classes. – Thilo Jul 11 '20 at 11:10
  • @Progman That code looks pretty complete and self-contained already. – Thilo Jul 11 '20 at 11:12
  • Also check https://stackoverflow.com/questions/2745265/is-listdog-a-subclass-of-listanimal-why-are-java-generics-not-implicitly-po – Progman Jul 11 '20 at 12:27
  • @Thilo I have included more information in "EDIT 1" to show you that it doesn't work at the moment. The generated classes by `immutables` library do not have a relationship such that `StudioAdvert extends Advert`, but instead it has `StudioAdvert implements AbstractAdvert.AbstractStudioAdvert`. – curiousdev Jul 11 '20 at 12:28
  • @Progman the first link answered my question - thanks. I've got some learning to do haha. – curiousdev Jul 11 '20 at 12:31

0 Answers0