简体   繁体   English

scala.Array 如何成为 Seq?

[英]How is scala.Array a Seq?

I'm a strong Java developer who has very recently started trying to pick up Scala in my free time.我是一个强大的 Java 开发人员,最近开始尝试在空闲时间学习 Scala。 I'm going through the Scala by Example PDF from scala-lang.org and am confused how the Quick Sort in the very first example works.我正在通过来自scala-lang.org 的示例PDF 浏览 Scala 并且对第一个示例中的快速排序如何工作感到困惑。 Here is the code:这是代码:

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.我的问题不在于语法或任何东西,但我对过滤器 function 的来源感到困惑。 According to the PDF, it says that it comes from the Seq[T] class, and that all Arrays are instances of Seq[T].根据 PDF,它说它来自 Seq[T] class,并且所有 Arrays 都是 Seq[T] 的实例。 That is all fine and dandy and while reading the PDF I was satisfied and a very happy newbie Scala developer.这一切都很好,而且在阅读 PDF 时我很满意,并且是一个非常高兴的新手 Scala 开发人员。 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.但后来我挖得更深一点,开始查看 Array[T] 的scaladoc 以及 Array[T]的源代码,但我看不到 Array[T] class 如何扩展或继承 Seq[T] 特征全部。 What am I missing?我错过了什么?

You are missing implicits.你缺少隐式。 There's a few questions about implicits on Stack Overflow.关于 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 Array as input parameter and return something else.在您正在阅读的 PDF 上,请参阅第 15 章,从第 113 页开始。在 Scaladoc 上,您将看到 object scala.Predef作为输入参数的其他隐式方法并返回其他隐式方法,这些方法采用 Predef Array作为输入参数。 .

PS: Yikes, it says Array is a Seq . PS:哎呀,它说Array is a Seq That might have been the case before Scala 2,8, actually, but since then an Array is a Java Array , pure and simple.实际上,在 Scala 2,8 之前可能就是这种情况,但从那时起, Array就是 Java Array ,纯粹而简单。

There's an implicit conversion to WrappedArray in Predefs. Predefs 中有对 WrappedArray 的隐式转换。 See Scala Arrays vs Vectors .请参阅Scala Arrays 与向量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM