generic functor class in java

functor, generics, java

Solution

Because generics are implemented in Java by erasing the type information (in `class C<T>`, `T` goes 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>` and `F<T1,T2>` and load them both, some class `C`, 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 let `T` be the object, a `Pair<T1, T2>` object, a `ThreeTuple<T1, T2, T3>` etc. Scala does this.

Problem

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?

Original source