Skip to content

Instantly share code, notes, and snippets.

@nschlimm
Last active February 5, 2019 08:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nschlimm/429275da2fddc8837745c3f5930f8fc5 to your computer and use it in GitHub Desktop.
Save nschlimm/429275da2fddc8837745c3f5930f8fc5 to your computer and use it in GitHub Desktop.
Type Inference on Method chaining
public class SomePojo<T> {
private String someProperty;
private String anotherProperty;
private SomePojo(Builder<T> builder) {
this.someProperty = builder.someProperty;
this.anotherProperty = builder.anotherProperty;
}
public static void main(String[] args) {
// Type mismatch: cannot convert from SomePojo<Object> to SomePojo<String>
SomePojo<String> pojo = SomePojo.builder().build();
// Works fine
SomePojo<String> another = SomePojo.builder().buildWithOwnTypeParameter();
}
/**
* Creates builder to build {@link SomePojo}.
* @return created builder
*/
public static <T> Builder<T> builder() {
return new Builder<T>();
}
/**
* Builder to build {@link SomePojo}.
*/
public static final class Builder<T> {
private String someProperty;
private String anotherProperty;
private Builder() {
}
public Builder<T> withSomeProperty(String someProperty) {
this.someProperty = someProperty;
return this;
}
public Builder<T> withAnotherProperty(String anotherProperty) {
this.anotherProperty = anotherProperty;
return this;
}
public SomePojo<T> build() {
return new SomePojo<T>(this);
}
@SuppressWarnings("unchecked")
public <O> SomePojo<O> buildWithOwnTypeParameter() {
return new SomePojo<O>((Builder<O>) this);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment