[Haskell-cafe] Re: What I wish someone had told me...
robgreayer at yahoo.com
Thu Oct 16 12:48:20 EDT 2008
> On Thu, 2008-10-16 at 15:02 +1300, Richard O'Keefe
> > On 16 Oct 2008, at 12:09 pm, Jonathan Cast wrote:
> > >> I am not sure how say in a Java language a
> constructor can "conjure
> > >> up
> > >> a value of an unknown type".
> > >
> > > Well, that's the point. It can't, in
> Haskell or in Java. If you
> > > understand that --- that you can't call the
> default constructor of a
> > > class that is not statically known at compile
> > If you understand that about Java, then you don't
> understand Java.
> God, I hope never to understand Java. *shudder*
> > Java reflection means that compile-time types are
> backed up by
> > runtime objects belonging to Type in general, to Class
> if they
> > are class types. It also means that you can discover
> > default constructor by using aClass.getConstructor(),
> and you
> > can invoke it by using .newInstance().
> Wait, what? Why can't Java use this to keep template
> parameters around
> at run time? Or is the article (as per which
> Set<Integer> and
> Set<Double> are identical at run time) full of it?
The article (whichever it was) wasn't full of it... Set<Integer> and Set<Double> are identical at runtime. You cannot, given a Class object at runtime that happens to be the Class object corresponding to Set<?>, conjure up an instance of Set... but simply for the reason that Set has no constructors (it is an interface). You can, however, given a class object that happens to be the class object corresponding to (say) HashSet, conjure up an instance of a HashSet, and assign it to a variable of the (static) type Set<Integer> or Set<Double>... i.e.
Set<Integer> foo = (Set<Integer>) hashSetClass.newInstance();
Set<Double> bar = (Set<Double>) hashSetClass.newInstance();
which will generate warnings about unsafe casts, but nevertheless can compile, and won't cause any exceptions at runtime.
More information about the Haskell-Cafe