4

I am trying the following code in Scala, which is coming from An Overview of the Collections API.

import collection._
scala> Traversable(1, 2, 3)
res5: Traversable[Int] = List(1, 2, 3)
scala> Iterable("x", "y", "z")
res6: Iterable[String] = List(x, y, z)
scala> Map("x" -> 24, "y" -> 25, "z" -> 26)
res7: scala.collection.Map[String,Int] = Map(x -> 24, y -> 25, z -> 26)
scala> SortedSet("hello", "world")
res9: scala.collection.SortedSet[String] = TreeSet(hello, world)
scala> IndexedSeq(1.0, 2.0)
res11: IndexedSeq[Double] = Vector(1.0, 2.0)

The result shows that those trait can all call its apply method to create an instance of its implementation. But after looking for scala.collection.package object, I found nothing. I think there must be somewhere that binds those trait to its subclass and imports to my program. Can someone explain where it is?

1 Answer 1

7

You're calling apply on the trait's companion object, not on the trait.

For example, Traversable:

If you click on apply in the companion object's scaladoc, you can see that the Traversable object inherits its apply method from GenericCompanion, which has a link to the source so you can see how it's implemented.

Sign up to request clarification or add additional context in comments.

4 Comments

but there is not apply method in the companion object of Traversable?
There is. Look at the second link. It's the second item listed in the "Value Members" section.
oh, I see. The apply method is extends from TraversableFactory.
If you click on apply, you can see that the Traversable object inherits its apply method from GenericCompanion, which has a link to the source so you can see how it's implemented.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.