Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FEATURE] covariant override of chained setters in subclass #3731

Open
jhannes opened this issue Aug 23, 2024 · 0 comments
Open

[FEATURE] covariant override of chained setters in subclass #3731

jhannes opened this issue Aug 23, 2024 · 0 comments

Comments

@jhannes
Copy link

jhannes commented Aug 23, 2024

When I create type hierarchies of data-types with chainable setters, setting a property on the superclass will return the type of the superclass. This means that I cannot subsequently call methods on the subclass. As Java supports covariant return types, this can be fixed with a simple matter of code generation

Describe the feature

Considering the following classes

@Data
public class Pet {
    private String name;
}

@Data
public class Dog extends Pet {
   private String breed;
}

Given lombok.accessor.chain=true , the following compiles:

new Dog().setBreed("Labradoodle").setName("Fido");

But this does not compile, because setName has return type Pet:

new Dog().setName("Fido").setBreed("Labradoodle");

Either by default or with a flag, the following code could be generated:

public class Pet {
    private String name;
    public String getName() {
         return this.name;
    }
    public Pet setName(String name) {
         this.name = name;
         return this;
    }
}

public class Dog extends Pet {
    private String breed;
    public String getBreed() {
         return this.breed;
    }
    public Dog setBreed(String breed) {
         this.breed = breed;
    }

    /* THIS IS THE PROPOSED CHANGE; covariant override of chained setter */
    @Override
    public Dog setName(String name) {
         super.setName(name);
         return this;
    }
}

Describe the target audience

This is useful for Data classes in hierarchies with chaining setters.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant