Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define generic interfaces with same name but a different number of type parameters in Java

In Java (1.7), is it possible to define multiple interfaces with the same name, but with a different number of type parameters? What I'm essentially looking for is in spirit similar to the Func<TResult>, Func<T1, TResult>, Func<T1, T2, TResult>, Func<T..., TResult> delegate types of .NET. Very much like optional type parameters.

Exists such a functionality in the Java language or am I limited to creating different interfaces with names such as Func0<TResult>, Func1<T1, TResult>, Func2<T1, T2, TResult>?

like image 224
knittl Avatar asked Oct 01 '22 04:10

knittl


2 Answers

Generic types are a compile time feature, this means that at runtime your Func classes would all be the same class. Even if you compiled them individually and added them to your class path, only one would load. This means they have to have different full class names to be used at runtime.

like image 112
Peter Lawrey Avatar answered Oct 04 '22 20:10

Peter Lawrey


You can't have a variable number of generic type parameters, but you can "force" a parameter to be ignored by using the Void type for it:

interface Func<T1, T2, IReault> {...}
interface Func1<T1, IResult> extends Func<T1, Void, IResult> {...}
interface Func0<IResult> extends Func<Void, Void, IResult> {...}

Void can't be instantiated, so the only valid Void reference you can pass/return/use is null, thus enforcing that the Void parameter is effectively ignored in both the implementation and the caller.

Instances of Func1 and Func0 are still instances of Func.

like image 39
Bohemian Avatar answered Oct 04 '22 19:10

Bohemian