Self-type
Alex Buckley
alex.buckley at oracle.com
Tue Jun 16 22:53:04 UTC 2015
Because the "B this" term in your method signature is a receiver
parameter. Per JLS8 8.4.1, a receiver parameter "represents the object
for which the method is invoked" and "exists solely to allow the type of
the represented object to be denoted in source code, so that the type
may be annotated." The only type permitted for a receiver parameter is
the enclosing class, i.e., a self type but not with the generality you
desire.
Alex
On 6/16/2015 2:23 AM, Timo Kinnunen wrote:
> How come this simple and obvious thing doesn’t work?
>
>
> <B> B init(B this, T value) {
>
> this.item = value;
>
> return this;
>
> }
>
>
> To me that says: “whatever type you used as a receiver, you get the same back”, as simple as that. The equivalent static method version works as expected but isn’t as convenient to use for consumers:
>
>
> static <B extends Box<T>, T> B init2_OK(B thiz, T value) {
>
> thiz.item = value;
>
> return thiz;
>
> }
>
>
> This similar construct works as well but requires extra discipline from the consumer:
>
>
> <B> B init3_OK(B thiz, T value) {
>
> this.item = value;
>
> return thiz;
>
> }
>
>
> This is the closest I have gotten to a workaround, but it is obviously not completely type-safe:
>
>
> <B extends Box<T>> B init4_OKISH(T value) {
>
> this.item = value;
>
> return thiz();
>
> }
>
> private <B extends Box<T>> B thiz() {
>
> @SuppressWarnings("unchecked")
>
> B thiz = (B) this;
>
> return thiz;
>
> }
>
>
> A little help from the language, please?
>
>
>
>
>
More information about the jdk9-dev
mailing list