为什么reduceLeft 的类型参数包含下界? [英] Why does the type parameter of reduceLeft contain a lower bound?

查看:42
本文介绍了为什么reduceLeft 的类型参数包含下界?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

reduceLeft 在某些 Seq[A] 上的签名是

The signature of reduceLeft on some Seq[A] is

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

A 的类型是已知的,但是下界 >: 告诉我们 B 可以是 的任何超类型A.

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

我们已经知道序列的头部是 A 类型,所以我想不出 B 怎么可能不等于 A.你能提供一个例子,其中 B 是某种超类型吗?

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?

推荐答案

假设你的类 B 有一个方法 combine(other:B): B.现在您在 A 列表上调用 reduceLeft((b,a) => b.combine(a)).由于combine的返回类型是BreduceLeft的类型参数需要是B.

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.

这篇关于为什么reduceLeft 的类型参数包含下界?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆