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

Builder returns wrong type for generics #1502

Closed
lludwa opened this issue Oct 24, 2017 · 3 comments
Closed

Builder returns wrong type for generics #1502

lludwa opened this issue Oct 24, 2017 · 3 comments

Comments

@lludwa
Copy link

lludwa commented Oct 24, 2017

Lombok version: 1.16.18

Using Lombok builder on generics gives compilation error, related with wrong types:

public class Main {
    
    public static abstract class Animal {
    }

    public static class Dog extends Animal {
    }

    @Getter
    @Setter
    public static class SimpleBuilder<ANIMAL extends Animal> {
        private ANIMAL animal;
    }

    @Getter
    @lombok.Builder
    public static class LombokBuilder<ANIMAL extends Animal> {
        private ANIMAL animal;
    }

    public static void main(String[] args) {
        //COMPILES OK:
        final SimpleBuilder<Dog> simpleBuilder = new SimpleBuilder<>();
        simpleBuilder.setAnimal(new Dog());

        //COMPILATION ERROR:
        final LombokBuilder<Dog> lombokBuilder = LombokBuilder.builder().animal(new Dog()).build();
    }
}

LombokBuilder gives upcoming error:

Required: LombokBuilder <Dog>
Found: LombokBuilder <Animal>
@victorwss
Copy link
Contributor

Possibly related with #1420.

@rspilker
Copy link
Collaborator

rspilker commented Jan 9, 2018

The problem has to do with the type inference. It doesn't carry as far as you seem to think. The call to LombokBuilder.builder() does not have any clue on what you're going to put in. So you need to help the compiler a bit to make it compile:

final LombokBuilder<Dog> lombokBuilder = LombokBuilder.<Dog>builder().animal(new Dog()).build();

I don't think that this is a lombok problem.

@rspilker rspilker closed this as completed Jan 9, 2018
@laffuste
Copy link

laffuste commented Nov 7, 2019

You can get a slightly less dry syntax adding in your class with a @Builder:

public static <T extends Animal> Owner.OwnerBuilder<T> builder(Class<T> cls) { return new Owner.OwnerBuilder<>(); }

(I changed the example class name LombokBuilder to Owner for clarity)

Now you can use the builder like:

// Owner<Dog> owner = Owner.<Dog>builder().animal(new Dog()).build();
Owner<Dog> owner = Owner.builder(Dog.class).animal(new Dog()).build();

Wohoo, almost the same :/

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

4 participants