第3章 ラムダ式を使ったプログラミング : 問題 19 : Stream の reduce メソッド
問題
Stream<T>
のreduce
メソッドは、以下のように宣言している
<U> U reduce(U identify, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner)
accumulator
の型を
BiFunction<? super U, ? super T, U> accumulator
と宣言すべきか?
解答
No ! である
Stream<T>
のreduce
メソッドの Java Doc にあるように、accumulator
は以下のように使われる
■ Stream<T>
のreduce
メソッドの実装イメージ
U result = identify; for (T element : stream) { result = accumulator.apply(result, element); } return result;
これを見るとaccumulator
のapply
メソッドの第一引数の型は常に U で、U の親クラスになることはないのだ
数学的帰納法だと
result
の最初の値はidentify
なので、型は U- その後の
result
はapply
メソッドの戻り値なので、型は U - つまり、どこまで行っても
result
の型は U
というふうに証明できる :-)