为什么reduceLeft 的类型参数包含下界?

编程入门 行业动态 更新时间:2024-10-25 23:23:36
本文介绍了为什么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) => bbine(a)).由于combine的返回类型是B,reduceLeft的类型参数需要是B.

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

更多推荐

为什么reduceLeft 的类型参数包含下界?

本文发布于:2023-11-16 09:48:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1603178.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:下界   参数   类型   reduceLeft

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!