Home > front end >  Why are generic types unable to be declared as a return type in static methods?
Why are generic types unable to be declared as a return type in static methods?

Time:09-17

I understand why I'm unable to pass in the parameter InterestPoint<M> to the second method because of its static nature, but why does an error occur when I try to declare it as the return type? Removing the type parameter fixes this but then I'm left with the warning: Raw use of parametrized class 'InterestPoint'.

public record InterestPoint<M>(Coordinate coordinate, M marker) {

    public final InterestPoint<M> validate() {

        return this;
    }

    public static final InterestPoint<M> validate(InterestPoint interestPoint) {

        interestPoint.validate();
        return interestPoint;
    }
}

CodePudding user response:

The M generic type parameter belongs to an instance, whereas a static method doesn't belong to a specific instance, but to a class. The way to have a static method return a generic type is to add a type parameter to it directly. E.g.:

public static final <N> InterestPoint<N> validate(InterestPoint<N> interestPoint) {
    interestPoint.validate();
    return interestPoint;
}
  • Related