Learn Hadoop
Learn Hadoop

Reputation: 3050

Scala Array is subtype of Sequence

How seq is accepting Array parameter input doPrint function.

def doPrint(x : Seq[Any]) : Unit ={
   x.foreach(println)
}

doPrint(List(1,32,4))
doPrint(Array(1,2,3,4,5,6))

List is subtype Seq , Not Array.How it is working?

Upvotes: 0

Views: 222

Answers (2)

Constantine
Constantine

Reputation: 1406

Two implicit conversions exists for Array: scala.collection.mutable.ArrayOps and scala.collection.mutable.WrappedArray.

In case of 2nd method call, Array is implicitly converted to WrappedArray which is subtype of Seq.

Upvotes: 1

bobah
bobah

Reputation: 18864

It's thanks to an implicit conversion to a WrappedArray.

From here (many examples there):

Scala 2.8 array implementation makes systematic use of implicit conversions. In Scala 2.8 an array does not pretend to be a sequence. It can't really be that because the data type representation of a native array is not a subtype of Seq. Instead there is an implicit "wrapping" conversion between arrays and instances of class scala.collection.mutable.WrappedArray, which is a subclass of Seq.

Upvotes: 3

Related Questions