I’d like to have functor class like this:
public class Functor<T, R> {
public R invoke(T a) { ... }
}
And another class for the 2 arguments:
public class Functor<T1, T2, R> {
public R invoke(T1 a, T2 b) { ... }
}
And so on.
In C# i can write:
class Functor<T> { ... }
class Functor<T1, T2> { ... }
But in Java it would be an error:
The type Functor is already defined
What are best practices for multi-arguments generic classes in java?
Because generics are implemented in Java by erasing the type information (in
class C<T>,Tgoes away in the compiled .class file) there is no way for the compiler to know what class you are talking about at runtime.If you define
F<T1>andF<T1,T2>and load them both, some classC, could not identify the one it wanted to use.This is the long way around saying, I don’t think you can do that in Java. :\
What you might want to do is simply have a single argument functor
F<T>and letTbe the object, aPair<T1, T2>object, aThreeTuple<T1, T2, T3>etc. Scala does this.