Self-type

Timo Kinnunen timo.kinnunen at gmail.com
Tue Jun 16 09:23:47 UTC 2015


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?





-- 
Have a nice day,
Timo.

Sent from Windows Mail


More information about the jdk9-dev mailing list