Generics fail when builder set on method

6 views
Skip to first unread message

Morten Sabroe Mortensen

unread,
Jun 25, 2024, 10:28:54 AM (4 days ago) Jun 25
to Project Lombok
Hi all,

I have always praised Lombok for its ability to handle generics upon builders. However, not I have an examples which tries to tell me otherwise.

Below are two examples:
  • Class XXX with a builder on the main class. All good, type-wise.
  • Class XXX2 with a build on a method. Type-wise, all generics are havoc.
I am mostly disappointed that this second example does not work. And it also does not work if the name of generics on the MapBuilder is X, K, V, just harder to see through.

Are anyone aware of this construction? I believe that I could make this work very well if I coded it by hand -- handle this case of not having class-global generic types in play.

Am I off somewhere?

I am no novice to Java nor Lombok.

Kind Regards,
Morten Sabroe Mortensen

----
import lombok.AllArgsConstructor;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

@lombok.Builder(builderClassName="MapBuilder")
@AllArgsConstructor
public class XXX<X,K,V> {
    private final X x;
    private final Consumer<Map<K,V>> consumer;

    public static class MapBuilder<X2,K2,V2> {
        public X2 commit() {
            XXX<X2,K2,V2> c=build();
            HashMap<K2,V2> map=new HashMap<>();
            consumer.accept(map);
            return x;
        }
    }
}
-----
import lombok.experimental.UtilityClass;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

@UtilityClass
public class XXX2 {
    @lombok.Builder(builderClassName="MapBuilder")
    private static <X,K,V> Map<K,V> createMap(X x,
                                              Consumer<Map<K,V>> consumer) {
        return new HashMap<>();  //Whatever
    }

    public static class MapBuilder<X2,K2,V2> {
        public X2 commit() {
            Map<K2,V2> map=build();  //Error; #build() returns Map<K,V>!
            consumer.accept(map);    //Error; #consumer.acceps() fit Map<K,V>!
            return x;                //Errror; provided type is 'X', not 'X2'!
        }
    }

    public static void main(String[] args) {
        MapBuilder<String,Integer,Boolean> builder=builder();  //Error; provided is MapBuilder<X2.K2.V2>!
    }
}
-----
Reply all
Reply to author
Forward
0 new messages