Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is scala.Array a Seq?

Tags:

scala

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 Example PDF from scala-lang.org and am confused how the Quick Sort in the very first example works. 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. 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?

like image 213
johnmcase Avatar asked May 29 '11 01:05

johnmcase


2 Answers

You are missing implicits. There's a few questions about implicits on 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.

PS: Yikes, it says 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.

like image 190
Daniel C. Sobral Avatar answered Nov 17 '22 01:11

Daniel C. Sobral


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

like image 38
Kevin Avatar answered Nov 17 '22 01:11

Kevin