Why do traits in scala.collection instantiate?

I am trying to use the following code in Scala, which comes from the Collection API Overview .

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 this feature can call its method applyto create an instance of its implementation. But after searching for the object, scala.collection.packageI did not find anything. I think there should be somewhere that ties this trait to a subclass and imports into my program. Can someone explain where this is?

+4
source share
1 answer

You call applyinto the companion object of the object, not to the hell.

For example Traversable:

apply , , Traversable GenericCompanion, , , .

+7

All Articles