Search code examples
java-8generic-type-argument

Why is there formal parameter type in static method Stream.empty() although there is no parameter in the method?


Formal parameter type is allowed in Java 8 and, it is usually used when there are parameters with generic types AFAIK.

However, there are indeed some methods without parameters but formal parameter type anyway. For instance,

<T> Stream<T> java.util.stream.Stream.empty()

Anyone can explain on this?


Solution

  • The generic type argument is required here to specify the element type of the returned empty Stream. Otherwise this method would return a raw Stream type.

    For example:

    Stream<String> stream = Stream.empty();