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?
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.
There's an implicit conversion to WrappedArray in Predefs. See Scala Arrays vs Vectors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With