Why do generic methods and generic types have different type introduction syntax?

Viewed 3119

While studying generics, I noticed a difference in type introduction syntax between generic methods and generic types (class or interface) that confused me.

The syntax for a generic method is

<T> void doStuff(T t) {
    // Do stuff with T
}

The docs say

The syntax for a generic method includes a type parameter, inside angle brackets, and appears before the method's return type

The syntax for a generic type is

class Stuff<T> {
    // Do stuff with T
    T t;
}

The docs say

The type parameter section, delimited by angle brackets (<>), follows the class name. It specifies the type parameters

For neither it states why it must come before or after.


In order to be consistent with each other, I expected either the method syntax to be
void doStuff<T>(T t) {}or the type syntax (for class) to be class <T>Stuff {}, but that is obviously not the case.

Why does the one have to be introduced before, and the other after?

I have used generics mostly in the form of List<String> and argued that <String>List might look weird, but that is a subjective argument, besides for methods it is like that as well. You can call doStuff like this.<String>doStuff("a string");

Looking for a technical explanation I thought perhaps <T> must be introduced to a method before specifying the return type because T might be the return type and the compiler maybe isn't able to look ahead like that, but that sounded odd because compilers are smart.

I figure there is an explanation for this beyond "the language designers just made it that way", but I could not find it.

7 Answers
Related