maks
maks

Reputation: 6006

Common in scala's Array and List

I'm new to scala(just start learning it), but have figured out smth strange for me: there are classes Array and List, they both have such methods/functions as foreach, forall, map etc. But any of these methods aren't inherited from some special class(trait). From java perspective if Array and List provide some contract, that contract have to be declared in interface and partially implemented in abstract classes. Why do in scala each type(Array and List) declares own set of methods? Why do not they have some common type?

Upvotes: 1

Views: 288

Answers (2)

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297275

I'll extend om-nom-nom answer here.

Scala doesn't have an Array -- that's Java Array, and Java Array doesn't implement any interface. In fact, it isn't even a proper class, if I'm not mistaken, and it certainly is implemented through special mechanisms at the bytecode level.

On Scala, however, everything is a class -- an Int (Java's int) is a class, and so is Array. But in these cases, where the actual class comes from Java, Scala is limited by the type hierarchy provided by Java.

Now, going back to foreach, map, etc, they are not methods present in Java. However, Scala allows one to add implicit conversions from one class to another, and, through that mechanism, add methods. When you call arr.foreach(println), what is really done is Predef.refArrayOps(arr).foreach(println), which means foreach belongs to the ArrayOps class -- as you can see in the scaladoc documentation.

Upvotes: 3

om-nom-nom
om-nom-nom

Reputation: 62855

But any of these methods aren't inherited from some special class(trait)

That simply not true.

If you open scaladoc and lookup say .map method of Array and List and then click on it you'll see where it is defined:

For list:

enter image description here

For array:

enter image description here

See also info about Traversable and Iterable both of which define most of the contracts in scala collections (but some collections may re-implement methods defined in Traversable/Iterable, e.g. for efficiency).

You may also want to look at relations between collections (scroll to the two diagrams) in general.

Upvotes: 8

Related Questions