流映射的签名

huangapple go评论76阅读模式
英文:

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,该流拦截基础流中的元素,并在继续之前应用该函数,因此遇到的所有元素现在将是类型 R。

由于原始流迭代的是类型为 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&lt;T&gt;{ ... &lt;R&gt; Stream&lt;R&gt; map(Function&lt;? super T, ? extends R&gt; 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.

&lt;NEW_STREAM_TYPE&gt; Stream&lt;NEW_STREAM_TYPE&gt; map(Function&lt;? super CURRENT_STREAM_TYPE, ? extends NEW_STREAM_TYPE&gt; modifier);

huangapple
  • 本文由 发表于 2020年9月19日 20:09:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/63968629.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定