One limitation of Java generics is that you can't have polymorphic data within a method. But there is a workaround of declaring a static class within a method. The Java record syntax let's you do this without creating a new inner class object. Hopefully the inner class limitation on classes declared inside a method is lifted.
int myfunction(int x) { record Id() { static <A> id(A input) { A value = input; return value; } } return Id.id(x); }
It's a bit awkward but sometimes useful in heavily polymorphic code.
Top comments (0)