[Haskell-cafe] Re: What I wish someone had told me...

Jonathan Cast jonathanccast at fastmail.fm
Thu Oct 16 14:44:43 EDT 2008

On Thu, 2008-10-16 at 11:41 -0700, Robert Greayer wrote:
> --- On Thu, 10/16/08, Jonathan Cast <jonathanccast at fastmail.fm> wrote:
> > But I can't say new HashSet<?>()?
> > 
> No... but you can say 'new HashSet<T>()' where T is a type variable,
> and then put a value of type T into your set, which is probably
> generally what you want.  HashSet<?> is a set of unknown (at compile
> time) element type.  It is not safe to put any element into such a
> set.  Consider:
> void wrong(List<?> foo, List<?> bar) {
>    foo.add(bar.get(0)); // illegal... but if it weren't...
> }

So if I say

void wrong(List<?> foo, List<?> bar)

I get two /different/ type variables implicitly filled in?

If I declare a generic class, and then have a method, is there a way, in
that method's parameter list, to say `the type parameter that was
supplied when my class was instantiated'?

> ...
> List<Integer> x = ...;
> List<String> y = ...;
> wrong(x, y); // then this would put an String into a list of ints...

Yikes.  So, in this instance, the difference between Haskell and Java
is: if you want to disallow that call to wrong, in Haskell you can...

> ---

> Perhaps there was confusion over what you meant by 'conjure up a value
> of an unknown type'... you can't explicitly instantiate a
> parameterized class with a wildcard type variable (e.g. new
> HashSet<?>).

Right.  Which is a logical consequence of parametric polymorphism.

> However, you can conjure up an instance of any class for which you
> have a Class object handy, provided it is non-abstract and has public
> constructors, and then assign it to a variable with a wildcard in its
> type.

(Which is a logical consequence of non-parametric polymorphism,
concerning which: yikes!)


More information about the Haskell-Cafe mailing list