i have interface type parameter allows conversion same type type parameter. this:
interface interfaze<a> { public <b> interfaze<b> convert(java.util.function.function<a, b> f); }
i want impose stricter requirement on return type: want convert
method return same type called on. this:
class goodinterfaze<a> implements interfaze<a> { public <b> interfaze<b> convert(java.util.function.function<a, b> f) { // return new goodinterfaze<b>(); // want allowed compiler // return new badinterfaze<b>(); // want compilation error return null; } } class badinterfaze<a> implements interfaze<a> { public <b> interfaze<b> convert(java.util.function.function<a, b> f) { // return new goodinterfaze<b>(); // want compilation error // return new badinterfaze<b>(); // want allowed compiler return null; } }
the interfaze
interface under control, can add type parameters (or methods) when needed. java generics allow this?
you can close doing this.
public interface interfaze<t extends interfaze<t>> { t convert(); }
then can do
public class main { public static class implements interfaze<good> { @override public convert() { return new good(); } // compiles } public static class bad implements interfaze<bad> { @override public bad convert() { return new good(); } // doesn't compile } }
this idea of using recursive bounds common. dislike it's confusing , because doesn't mix inheritance. example, can't make subclass subgood
of good
implements interfaze<subgood>
because can't implement same generic interface 2 different type arguments. works if implementing classes cannot extended (that's why enum<e extends enum<e>>
ok).
Comments
Post a Comment