Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce Self interface #801

Closed
jenetics opened this issue Oct 13, 2021 · 1 comment
Closed

Introduce Self interface #801

jenetics opened this issue Oct 13, 2021 · 1 comment
Assignees
Milestone

Comments

@jenetics
Copy link
Owner

jenetics commented Oct 13, 2021

Some classes/interface in the library are using recursive generic types, as a possibility to model a self type. Similar to the abstract Enum<E extends Enum<E>> type in the JDK. The Gene type is such a type.

public interface Gene<A, G extends Gene<A, G>> {
    G newInstance(final A value);
}

The purpose of this, as illustrated in the code snippet above, is to avoid casts when working with the interface definition alone and creating new instances of the concrete implemented type G. In a proper implementation, it is save to cast this to G. But this is a very implicit convention. Nobody prevents you from creating the following class.

class FooGene implements NumericGene<Double, DoubleGene> {
    ...
}

Instead of the correct declaration of

class FooGene implements NumericGene<Double, FooGene> {
    ...
}

To make the intention more explicit, the following interface is added

interface Self<S extends Self<S>> {
    @SuppressWarnings("unchecked")
    default S self() {
        return (S)this;
    }
}

It is still possible to create invalid implementations, but the interface allows to make the intended purpose more explicit, also via the Javadoc of the interface.

@jenetics jenetics added this to the v7.0.0 milestone Oct 13, 2021
@jenetics jenetics self-assigned this Oct 13, 2021
jenetics added a commit that referenced this issue Oct 13, 2021
@jenetics jenetics changed the title Introduce SelfAware interface Introduce Self interface Oct 13, 2021
jenetics added a commit that referenced this issue Oct 13, 2021
jenetics added a commit that referenced this issue Oct 19, 2021
jenetics added a commit that referenced this issue Oct 19, 2021
jenetics added a commit that referenced this issue Oct 19, 2021
jenetics added a commit that referenced this issue Oct 19, 2021
@jenetics
Copy link
Owner Author

Merged into r7.0.0 branch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant