Collections – Creating Collections From Scratch – Scala Documentation

  1. Home
  2. map design tutorials
  3. Collections – Creating Collections From Scratch – Scala Documentation

You have syntax List(1, 2, 3) to create a list of three integers and Map(‘A’ -&gt, 1, ‘C’ -&gt, 2) to create a map with two bindings. This is actually a universal feature of Scala collections. You can take any collection name and follow it by a list of elements in parentheses. The result will be a new collection with the given elements. Here are some more examples: “Under the covers” each of the above lines is a call to the apply method of some object. For instance, the third line above expands to So this is a call to the apply method of the companion object of the List class. That method takes an arbitrary number of arguments an constructs a list from them. Every collection class in the Scala library has a companion object with such an apply method. It does not matter whether the collection class represents a concrete implementation, like List, or Stream or Vector, do, or whether it is an abstract base class such as Seq, Set or Traversable. In the latter case, calling apply will produce some default implementation of the abstract base class. Examples: Besides apply, every collection companion object also defines a member empty, which returns an empty collection. So instead of List() you could write List.empty, instead of Map(), Map.empty, and so on. Descendants of Seq classes provide also other factory operations in their companion objects. These are summarized in the following table. In short, there’s Source.

Menu
whatsapp button