Why does the type parameter of reduceLeft contain a lower bound?

拈花ヽ惹草 提交于 2019-12-10 22:41:12

问题


The signature of reduceLeft on some Seq[A] is

def reduceLeft [B >: A] (f: (B, A) => B): B 

The type of A is known, but the lower bound >: tells us that B can be any supertype of A.

Why is it like this? Why not

def reduceLeft (f: (A, A) => A): A

We already know that the head of the sequence is type A and so I can't think of how B could be anything other than equal to A. Can you provide an example where B is some super-type?


回答1:


Let's say your class B has a method combine(other:B): B. Now you call reduceLeft((b,a) => b.combine(a)) on a list of As. Since the return type of combine is B the type parameter to reduceLeft needs to be B.



来源:https://stackoverflow.com/questions/8364763/why-does-the-type-parameter-of-reduceleft-contain-a-lower-bound

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!