I am writing a class to represent time series data, i.e. basically a map of pairs (Instant, T) for the general type T
interface TimeSeries<T> { void add(Instant when, T data); }
Some of the classes we deal with implement the interface
interface TimeStamped { Instant getTimeStamp(); }
and I want to provide a more convenient method in the TimeSeries interface to add such data items without specifying the time. 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 does not seem to be allowed by the language, because I cannot use type variables in intersection types . Is there any work that is not related to giving up static security? The only thing I can come up with is
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.
source share