英文:
Signature of stream Map
问题
为什么以下代码中:
<R> Stream<R> map(Function<? super T,? extends R> mapper)
不需要像以下代码一样定义 T:
<R,T> Stream<R> map(Function<? super T,? extends R> mapper)
英文:
Why does the following
<R> Stream<R> map(Function<? super T,? extends R> mapper)
not need to define T as well, as in
<R,T> Stream<R> map(Function<? super T,? extends R> mapper)
答案1
得分: 3
interface Stream<T> {
<R> Stream<R> map(Function<? super T, ? extends R> modifier);
}
由于流(Stream)是在给定类型 T 的元素上进行迭代的,因此 T 已经是已知的,并且对于所有实例级别的方法(类中的非静态方法)都是可见的。映射函数的目的是返回一个 Stream
由于原始流迭代的是类型为 T 的元素,因此传递一个希望输入为 T2 类型的映射函数(如果它是方法泛型而不是类泛型)是无效的。该函数必须期望输入为类型 T(或者是 T 的超类)。然而,对输出没有任何限制。因此,所提供的函数仅取决于当前流的类型。
```java
<NEW_STREAM_TYPE> Stream<NEW_STREAM_TYPE> map(Function<? super CURRENT_STREAM_TYPE, ? extends NEW_STREAM_TYPE> modifier);
英文:
interface Stream<T>{ ... <R> Stream<R> map(Function<? super T, ? extends R> modifier); ... }
Because Streams iterate over elements of a given type, T is already known and is visible to all instance level methods (non-static methods in the class). The purpose of the mapping function is to return a Stream<R> which intercepts elements in the base stream, and applies the function before continuing so all elements encountered will now be of type R.
Because the original stream iterates over elements of type T, passing a mapping function which expects inputs of T2 (if it were a method generic instead of class generic) is invalid. The function must expect inputs of type T (or a superclass of T). However, there are no restrictions needed on the output. As such, the function provided depends only on the type of the current stream.
<NEW_STREAM_TYPE> Stream<NEW_STREAM_TYPE> map(Function<? super CURRENT_STREAM_TYPE, ? extends NEW_STREAM_TYPE> modifier);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论