Java generics – differences between method declarations

What is the difference between the following two method declarations:

1. <R> Stream<R> myFunc(Function<? super T,? extends R> mapper);    
 2. Stream<R> myFunc(Function<? super T,? extends R> mapper);

For the second declaration to compile, I need to add type parameters to the class like this

public class MyGenericsTest<T,R>

In this case, the compiler ensures that the return type of myfunc is determined at compile time The compiler can also know from the method signature I wonder why these two declarations are treated differently by the compiler

Solution

By writing < R > stream < R > myfunc (function mapper), you tell the compiler:

>R is any class and is local to the method (by starting with < R > at the beginning) > stream with return type R > t is the class specified in the type parameter of mygenericstest < T > (if you don't specify it, it won't work because the compiler won't know t)

If you change to stream < R > myfunc (function mapper), R and T are not local (there is no < R, t > at the beginning of the method) and the compiler expects them to be defined as mygenericstest & lt; T,R>

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>