Say I have a 3 generic parameters:
public static interface Mapper<V,T,E> {
public void map(KeyValue<V> v, AsyncCallback<T,E> cb);
}
How can I make the parameters optional? How can I give the parameters default values if the user only supplies the first parameter?
Using TypeScript, that would look like:
public static interface Mapper<V,T = any,E = any> {
public void map(KeyValue<V> v, AsyncCallback<T,E> cb);
}
so if the user doesn't supply T and E, they default to any. Is there a way to do this with Java?
Like many languages, there is no optional or gradual typing in Java. The typing rules are probably complicated enough as it is. Nor are there default type arguments, but that doesn't seem to be the major issue here.
In your case, it looks like making the typing more client friendly solves the problem without having to go further. I am assuming the
E
inAsyncCallback
is for "exception" andT
is, as in GWT'sAsyncCallback
, for a method parameter.That allows any particular
Mapper
to take any applicableAsyncCallback
.We can be more explicit about the exception - useful if we need to define a
throws
anywhere.If a reference to a
Mapper
could take anyAsyncCallback
, declare it of typeMapper<V,Object,Throwable>
for someV
.If you desperately wanted a short form of
Mapper
with a concise declaration for you could introduce an adapter.If you wanted the same thing for
AsyncCallback
, it's a bit more difficult. There is no denotable opposite ofObject
(i.e. the type ofnull
).