In Java 8's stream library, I found an interesting issue in same methods in java.util.stream.Stream
:
static <T> Stream<T> empty()
As we can see that there is no parameter in the method signature. According to my understanding, in this case there should not be type parameter - <T>
- after the optional specifier -static
. For instance, in the method Optional<T> findAny()
, no type parameter is given as expected.
So could anyone explain why does static <T> Stream<T> empty()
contain a type parameter?
Let's first declare our own type, to better understand why:
static interface Stream<T> {
public static Stream<T> empty() { // will not compile here
return new Stream<T>() {
};
}
}
As this code is right now, it would not compile, saying that can not make a static reference to the non-static type T
, which IMO makes complete sense. That happens because the static context is completely independent from type parameters (this should answer your first question).
To fix this we need to add the type parameter to the method:
public static <T> Stream<T> empty() { // notice the extra <T>
return new Stream<T>() {
};
}
This will compile just fine, but there is a hidden problem - the class T
and the method T
are completely independent and have no relationship between them.
This could have been written like this with the exact same effect (and cleaner IMO):
public static <R> Stream<R> empty() {
return new Stream<R>() {
};
}
because you have this: return new Stream<R>()...
we have effectively made R
and T
equivalent, may be this being the reason why they still used T
in the declaration of empty()
instead of some other type.
Now let's apply the same logic to findAny
:
public <T> Optional<T> findAny();
this will generate a warning - that you are hiding the <T>
that is declared at the class level (Stream<T>
) and the one in the method. That happens because findAny
is not static and it uses the type parameter already declared - which you are hiding by introducing another <T>
that would have no relationship with the one form the class level.