Last active
February 5, 2019 08:23
-
-
Save nschlimm/429275da2fddc8837745c3f5930f8fc5 to your computer and use it in GitHub Desktop.
Type Inference on Method chaining
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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