scala.Array 如何是 Seq?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6165399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:02:39  来源:igfitidea点击:

How is scala.Array a Seq?

scala

提问by johnmcase

I'm a strong Java developer who has very recently started trying to pick up Scala in my free time. I'm going through the Scala by ExamplePDF from scala-lang.org and am confused how the Quick Sort in the very first example works. Here is the code:

我是一名强大的 Java 开发人员,最近开始尝试在空闲时间学习 Scala。我正在浏览来自 scala-lang.org的Scala by ExamplePDF 并且对第一个示例中的快速排序是如何工作的感到困惑。这是代码:

object QuickSort extends App {

  def sort(input: Array[Int]): Array[Int] = {
    if(input.length <= 1) input
    else
    {
      val pivot = input(input.length / 2)
      Array.concat(
          sort(input filter (pivot >)),
               input filter (pivot ==),
          sort(input filter (pivot <))
      )
    }
  }

  sort(Array(5, 4, 3, 2, 1)) foreach println
}

My question is not with the syntax or anything, but I am confused with where the filter function comes from. According to the PDF, it says that it comes from the Seq[T] class, and that all Arrays are instances of Seq[T]. That is all fine and dandy and while reading the PDF I was satisfied and a very happy newbie Scala developer. But then I dug a little deeper and started looking at the scaladoc for Array[T]and also the source code for Array[T] and I do not see how the Array[T] class extends or inherits the Seq[T] trait at all. What am I missing?

我的问题不在于语法或任何东西,但我对过滤器函数的来源感到困惑。根据 PDF,它说它来自 Seq[T] 类,并且所有数组都是 Seq[T] 的实例。这一切都很好,而且在阅读 PDF 时我很满意,并且是一个非常快乐的 Scala 新手开发人员。但后来我挖得更深一些,开始查看Array[T]scaladoc 以及 Array[T]的源代码,但我没有看到 Array[T] 类如何扩展或继承 Seq[T] 特性全部。我错过了什么?

回答by Daniel C. Sobral

You are missing implicits. There's a fewquestionsabout implicitson Stack Overflow. On the PDF you are reading, see chapter 15, starting on page 113. On Scaladoc, you'll see the relevant implicits on the object scala.Predef-- just look for implicit methods which take an Arrayas input parameter and return something else.

你缺少隐式。Stack Overflow 上有一些关于隐式的问题。在您正在阅读的 PDF 上,请参阅第 15 章,从第 113 页开始。在 Scaladoc 上,您将看到对象上的相关隐式——只需查找将一个作为输入参数并返回其他内容的隐式方法。scala.PredefArray

PS: Yikes, it says Arrayis a Seq! That might have been the case before Scala 2.8, actually, but since then an Arrayis a Java Array, pure and simple.

PS:哎呀,上面写着Array是一个Seq!实际上,在 Scala 2.8 之前可能就是这种情况,但从那时起 anArray就是 Java Array,纯粹而简单。

回答by Kevin

There's an implicit conversion to WrappedArray in Predefs. See Scala Arrays vs Vectors.

在 Predefs 中有一个到 WrappedArray 的隐式转换。请参阅Scala 数组与向量