views:

60

answers:

2

Hello, recently I'm writing some functions that I take from Haskell and translate into Java. One of the main problems I have is I cannot easily create a static property with a generic type. Let me explain by a little example...

// An interface to implement functions
public interface Func<P, R> {
    public R apply(P p);
}

// What I want to do... (incorrect in Java)
public class ... {
    public static <T> Func<T, T> identity = new Func<T, T>() {
        public T apply(T p) { return p; }
    }
}

// What I do right now
public class ... {
    private static Func<Object, Object> identity = new Func<Object, Object>() {
        public Object apply(Object p) { return p; }
    }
    @SuppressWarnings("unchecked")
    public static <T> Func<T, T> getIdentity() {
        return (Func<T, T>)identity;
    }
}

Are there any easier ways to do something like that? What kind of problems might arise if the syntax I used would be valid?

+1  A: 

Just create a new tiny little object each time, for some definition of "each time". Remember that allocations on typical JREs are tiny, but GCing static data is expensive.

Whilst I think your syntax could be made to work without compatibility issues, it would be add complexity and irregularity whilst not bringing a huge amount on benefit.

Tom Hawtin - tackline
A: 

I think the way you're currently doing it is about the easiest you're going to find.

The issue is due to the way the Java Platform implements Generics internally -- since it uses type erasure (for backward compatibility reasons), type information is lost at compile time and prevents the usage of Generics in situations like static declarations, since those kinds of declarations typically require the type information to be compiled in (which Java currently won't do for Generics).

BCunningham
Here, it isn't necessary to have type information at runtime.
Chris
True, but I think from the Java compiler's perspective it's like trying to do "public static T foo = new T()" which isn't possible due to type erasure (that would effectively get translated as "public static foo = new Object()"...which definitely isn't right).
BCunningham