jeudi 27 juillet 2017

java type inference in builder pattern

i want to create a parameterized (generic) class MyType<T> and its builder. builder will have some methods that ignore the type T and some methods that use the type. but it seems like using this pattern i have to repeat the T declaration:

                     how to omit this declaration?
                                   |
                                   V
MyType<String> myType = Builder.<String>of()
                               .method1(argument_can_be_of_any_type)
                               .method2(argument_must_be_of_type_T)
                               .build();

is it possible to use some java syntax tricks or other design patterns to omit the second type declaration and make the API more user friendly? like for example:

List<String> aList = Lists.emptyList();

or

List<String> aList = new LinkedList<>();   

i don't want to enforce any order of methods in the builder

Aucun commentaire:

Enregistrer un commentaire