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

2

6

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>?

Lulualaba answered 2/8, 2014 at 9:19 Comment(4)
If if it were possible, what’s the advantage of declaring F<A> and F<A,B> over declaring F1<A> and F2<A,B>? They are two different types anyway. It would only make sense if you can declare the function’s method to have that magic type signature of taking all type arguments the class has. That boils down to the missing tuple type…Crashaw
I was just doing exactly the same thing and just ran into this same problem! I hate anonymous functions in java - 8 lines of code or something for what should be a one liner, still got to be done sometimesExpel
@JonnyLeeds: at least Java 8 finally has got lambdasLulualaba
yeah still not out for ee yet though I think. Also I think they are maintaining the wierd rules about final variables aswell which means you need to use arrays/fields everywhereExpel
B
3

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.

Bona answered 2/8, 2014 at 9:24 Comment(2)
So this basically boils down to "due to Java's type erasure it is not possible at all"?Lulualaba
Not AFAIK, This is usually handled by giving all the types e.g. Func<T1, T2, T3, T4, TResult> and providing Func<T1, T2, ?, ?, TResult> for two inputs. Using type inference in Java 8 hides much of this ugliness.Bona
E
1

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.

Eschew answered 2/8, 2014 at 22:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.