Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can traits in scala.collection create an instance?

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?

like image 669
ssj Avatar asked Mar 18 '23 00:03

ssj


1 Answers

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

For example, Traversable:

  • The trait

  • The object

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.

like image 69
Chris Martin Avatar answered Mar 20 '23 12:03

Chris Martin