Vinicius Seufitele
Vinicius Seufitele

Reputation: 895

Java defining covariant return from superclass

I have the following abstract class:

public abstract class AbstractSharpCollection<T> implements SharpCollection<T>

and an interface

public interface SharpCollection<T> extends Iterable<T>
{
    SharpCollection<T> tail();
}

There's a lot of other methods defined in SharpCollection, which return another SharpCollection. The logic of all those methods rely only on the iterator.

I want to be able to create a method on AbstractSharpCollection, such that the call to tail() would return the instance of the subclass, and not the superclass.

Something like

public <V extends SharpCollection<T>> V tail() { //code logic here }

I know that I can override the return type on the subclasses that extend the AbstractSharpCollection, but having to override all the methods only to change the return type is really ugly, troublesome, and prone to errors.

Is there any way at all that I can achieve what I want?

Thanks for the help.

Upvotes: 2

Views: 129

Answers (1)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

Implementing tail would be quite difficult. null is the only valid return value.

It appears you need to parameterise the SharpCollection so that it "knows" the actual interface type being used:

public interface SharpCollection<
    THIS extends SharpCollection<THIS, T>,
    T
> extends Iterable<T> {
    THIS tail();
}

Unfortunately this complicates the client code as well.

Upvotes: 2

Related Questions