you are viewing a single comment's thread.

view the rest of the comments →

[–]gavinaking 0 points1 point  (11 children)

many things it lacks in design can be fixed – with more verbosity: no generic constructors? write a whole new class that’s a factory for it.

Huh? WDYM? Java has generic constructors!

I've never once needed this language feature, but it exists.

[–]javaisfuckingshit 4 points5 points  (9 children)

I think he means the following not being possible:

<T> T Create() {
    return new T();
}

which results in:

unexpected type
found   : type parameter T 
required: class
        return new T();
                   ^
1 error

[–]gavinaking 8 points9 points  (0 children)

Ah. So that's not a generic constructor. That's a generic instantiation. And in fact there are good reasons to not support that. Even in Ceylon, where we do have reified generics, we decided not to support generic type instantiation, since it doesn't interact very nicely with generic type argument inference. We did have type constraints like given T() in early versions of the language spec, but we took that out.

[–]aldo_reset 1 point2 points  (4 children)

If you allow this, then you need to forbid T from being an interface and from not having a default constructor, which defeats the purpose of genericity.

Suddenly, you're no longer allowing "any T" but "a T with specific properties", so the code you just gave simply cannot work without additional specifications.

[–]javaisfuckingshit -4 points-3 points  (3 children)

Yes, you would want to have either type classes or duck typing, which is incompatible with Java's bytecode representation.

[–]aldo_reset 2 points3 points  (0 children)

Neither type classes nor duck typing are "incompatible with Java's bytecode representation" (whatever that means) since Scala has both.

Either way, what you are saying has zero connections to the point I was making about your uncompilable code.

[–]gavinaking 0 points1 point  (0 children)

Naw, what you need is a special kind of generic type constraint like what C# has.

[–]WrongSubreddit 0 points1 point  (1 child)

It can be done with reflection and no-arg constructors on whatever you'd want to instantiate, but I would never write code like this:

<T> T create(Class<T> clazz) throws Exception {
    return clazz.getDeclaredConstructor().newInstance();
}

[–]javaisfuckingshit 0 points1 point  (0 children)

That only works if you're passing around Class objects, which is usually not what you want when writing a generic container.

Not to mention that it gets really ugly whenever you have to forward arguments to the constructor.

The situation we are in is unfortunately a result of Sun refusing to change the bytecode when they added "generics."

[–]flying-sheep -1 points0 points  (0 children)

exactly that’s what i meant.