I am writing a class to represent time series data, i.e. basically a map of (Instant, T) pairs for a generic type T
interface TimeSeries<T> {
void add(Instant when, T data);
}
Some of the classes we deal with implement an interface
interface TimeStamped {
Instant getTimeStamp();
}
and I want to provide a more convenient method in the TimeSeries interface to add such data items without stating the time explicity. Basically, I want
interface TimeSeries<T> {
void add(Instant when, T data);
default <X extends T & TimeStamped> void add(X data) {
add(data.getTimeStamp(), data);
}
}
but this seems not allowed by the language because I cannot use type variables in intersection types. Is there a work-around that does not involve giving up static type-safety? The only things I can come up with are
interface TimeSeries<T> {
void add(Instant when, T data);
default void add(TimeStamped data) {
add(data.getTimeStamp(), (T)data);
}
default void add(TimeStamped t, T data) {
add(t.getTimeStamp(), data);
}
}
add(TimeStamped t, T data) is type-safe but still inconvenient.
interface TimeStampedTimeSeries<T extends TimeStamped> extends TimeSeries<T>- you could use it when populating the timeseries and when consuming it you could just refer toTimeSeries<?>.