在 Scala 中, Int 是 List[Int] 的超类型吗?

In Scala, is Int a super-type of List[Int] and how so?

看看这个例子:

val list = List(1, 2, 3, 4, 5) 
val sum = list.fold(0)((x, y) => x + y) 
assert(sum == 15)

以及fold的方法签名:

fold[A1 >: A](z: A1)(op: (A1, A1) => A1): A1

我假设 AList[Int] 类型,A1Int 类型。 根据 official docs for fold, A1 is a type parameter for the binary operator, a supertype of A. If my assumption above is correct, then Int is a super-type of List[Int] in the above sum example. Some blog posts like this one 实际上明确说明这一点。 显然,List[Int] 不会扩展 Int。所以我的问题是:IntList[Int] 的超类型吗?

A 是绑定在 List[+A] 类型构造函数本身中的类型变量:它位于您 link 编辑的文档页面的顶部,在

sealed abstract class List[+A]

您的 list-变量是 List[Int] 类型,因此 AIntfold 中的 A1 必须是 Int 的超类型,在这种情况下,AA1 >: A 因此都只是 Int(不是 List[Int])


关于博客的link:它确实包含了句子

Int is a supertype of List[Int]

这是完全错误的。您可以按如下方式轻松检查:

scala> implicitly[List[Int] <:< Int]
                 ^
       error: Cannot prove that List[Int] <:< Int.