You are on page 1of 3

Scala Cheat Sheet

1 Scala Class Hierarchy

Figure 2: scala.collection

Figure 1: Scala class hierarchy, source: http://www.


scala-lang.org/old/node/128

2 Scala Collections
2.1 Scala Collections Hierarchy

Figure 3: scala.collection.immutable Figure 4: scala.collection.mutable


2.2 Trait Traversable Category Methods 2.6 Map
Table 1: Methods in Traversable Indexing and xs(i), xs isDefinedAt i, xs.length, Table 7: Methods in Map
Category Methods Length xs.lengthCompare ys, xs.indices
Category Methods
Index Search xs indexOf x, xs lastIndexOf x, xs
Abstract xs foreach f indexOfSlice ys, xs lastIndexOfSlice ys, Lookup ms get k, ms(k), ms getOrElse (k, d), ms
Addition xs ++ ys xs indexWhere p, xs segmentLength (p, i), contains k, ms isDefinedAt k
Maps xs map f, xs flatMap f, xs collect f xs prefixLength p Addition ms + (k -> v), ms + (k -> v, l -> w), ms
Conversions toArray, toList, toIterable, toSeq, Addition x +: xs, xs :+ x, xs padTo (len, x) ++ kvs
toIndexedSeq, toStream, toSet, toMap Update xs patch (i, ys, r), xs updated (i, x), Removal ms - k, ms - (k, 1, m), ms -- ks
Size info isEmpty, nonEmpty, size, hasDefiniteSize xs(i) = x(only available for mutable.Seqs) Update ms updated (k, v)
Element head, headOption, last, lastOption, Sorting xs.sorted, xs sortWith lt, xs sortBy f Subcollection ms.keys, ms.keySet, ms.keyIterator,
Retrieval xs find p Reversal xs.reverse, xs.reverseIterator, xs ms.values, ms.valuesIterator
Sub- xs.tail, xs.init, xs slice (from, to), reverseMap f Transformation ms filterKeys p, ms mapValues f
collection xs take n, xs drop n, xs takeWhile p, xs Comparison xs startsWith ys, xs endsWith ys, xs Reference: http://docs.scala-lang.org/overviews/collections/maps.html
dropWhile p, xs filter p, xs withFilter p, contains x, xs containsSlice ys, (xs
xs filterNot p corresponds ys)(p)
Subdivision xs splitAt n, xs span p, xs partition p, xs Multiset xs intersect ys, xs union ys, xs diff ys, Table 8: Methods in mutable.Map
groupBy f xs.distinct
Element xs forall p, xs exists p, xs count p Category Methods
Reference: http://docs.scala- lang.org/overviews/collections/seqs.html
Condition Addition ms += (k -> v), ms += (k -> v, l -> w),
Fold (z /: xs)(op), (xs : z)(op), ms ++= kvs,
xs.foldLeft(z)(op), xs.foldRight(z)(op),
Table 4: Methods in Buffer
Removal ms -= k, ms -= (k, l, m), ms --= ks, ms
xs reduceLeft op, xs reduceRight op Category Methods remove k, ms retain p, ms.clear()
Specific Fold xs.sum, xs.product, xs.min, xs.max Update ms(k) = v, ms put (k, v), ms
String xs addString (b, start, sep, end), xs Addition buf += x, buf += (x, y, z), buf ++= xs, x
+=: buf, xs ++=: buf, buf insert (i, x), getOrElseUpdate (k, d)
mkString (start, sep, end), xs.stringPrefix Transformation ms transform f
View xs.view, xs view (from, to) buf insertAll (i, xs)
Removal buf -= x, buf remove i, buf remove (i, n), Cloning xs.clone
Reference: http://docs.scala-lang.org/overviews/collections/trait-traversable.html
buf trimStart n, buf trimEnd n, buf.clear()
Cloning buf.clone
2.3 Trait Iterable 2.7 Performance Characteristics
All methods in this trait are defined in terms of an an abstract 2.5 Set Table 9: Performance characteristics of sequence types
method, iterator, which yields the collections elements one by one. Table 5: Methods in Set head tail apply update prepend append insert
Category Methods immutable
Table 2: Methods in Iterable List C C L L C L -
Test xs contains x, xs(x), xs subsetOf ys
Stream C C L L C L -
Category Methods Addition xs + x, xs + (x, y, z), xs ++ ys
Vector eC eC eC eC eC eC -
Removal xs - x, xs - (x, y, z), xs -- ys, xs.empty
Abstract Stack C C L L C C L
xs.iterator Set operation xs & ys, xs intersect ys, xs | ys, xs union
Iterator xs grouped n, xs sliding n Queue aC aC L L L C -
ys, xs & ys, xs diff ys
Subcollection xs takeRight n, xs dropRight n Range C C C - - - -
Reference: http://docs.scala- lang.org/overviews/collections/sets.html
Zipper xs zip ys, xs zipAll (ys, x, y), String C L C L L L -
xs.zipWithIndex mutable
Mutable sets offer in addition methods to add, remove, or update ArrayBuffer C L C C L aC L
Comparison xs sameElements ys elements, which are summarized in below. ListBuffer C L L L C C L
Reference: http://docs.scala-lang.org/overviews/collections/trait-iterable.html
StringBuilder C L C C L aC L
Table 6: Methods in mutable.Set MutableList C L L L C C L
In the inheritance hierarchy below Iterable you find three traits: Queue C L L L C C L
Category Methods ArraySeq C L C C - - -
Seq, Set, and Map. A common aspect of these three traits is that
they all implement the PartialFunction trait with its apply and Addition xs += x, xs += (x, y, z), xs ++= ys, xs add Stack C L L L C L L
isDefinedAt methods. However, the way each trait implements x ArrayStack C L C C aC L L
PartialFunction differs. Removal xs -= x, xs -= (x, y, z), xs --= ys, xs Array C L C C - - -
remove x, xs retain p, xs.clear() Reference: http://docs.scala-lang.org/overviews/collections/performance- characteristics.html

2.4 Seq Update xs(x) = b


Cloning xs.clone
Table 3: Methods in Seq Table 10: Performance characteristics of set and map types
lookup add remove min 3.3 Concrete Parallel Collection Classes Sequential Parallel
immutable mutable.ParArray, immutable.ParVector, immutable.ParRange, mutable
HashSet/HashMap eC eC eC L Array ParArray
mutable.ParHashSet, mutable.ParHashMap, immutable.ParHashSet,
TreeSet/TreeMap Log Log Log Log HashMap ParHashMap
immutable.ParHashMap,
BitSet C L L eC 1 HashSet ParHashSet
ListMap L L L L mutable.ParTrieMap TrieMap ParTrieMap
mutable immutable
HashSet/HashMap eC eC eC L 3.4 Performance characteristics Vector ParVector
WeakHashMap eC eC eC L Range ParRange
BitSet C aC C eC 1 Table 11: Performance characteristics of sequence types HashMap ParHashMap
TreeSet Log Log Log Log head tail apply update prepend append insert HashSet ParHashSet
Footnote 1: Assuming bits are densely packed. Source: http://docs.scala- lang.org/overviews/parallel- collections/conversions.html
ParArray C L C C L L L
ParVector eC eC eC eC eC eC - Other collections, such as lists, queues or streams, are inherently
The entries in these two tables are explained as follows: ParRange C C C - - - - sequential in the sense that the elements must be accessed one after
C The operation takes (fast) constant time. http://docs.scala-lang.org/overviews/parallel- collections/concrete- parallel- collections.html the other. These collections are converted to their parallel variants
eC The operation takes effectively constant time, but this
by copying the elements into a similar parallel collection. For
might depend on some assumptions such as maximum
example, a functional list is converted into a standard immutable
length of a vector or distribution of hash keys. Table 12: Performance characteristics of set and map types parallel sequence, which is a parallel vector.
aC The operation takes amortized constant time. Some
lookup add remove Every parallel collection can be converted to its sequential variant
invocations of the operation might take longer, but if
using the seq method. Converting a parallel collection to a
many operations are performed on average only con- immutable sequential collection is always efficient it takes constant time.
stant time per operation is taken. ParHashSet/ParHashMap eC eC eC Calling seq on a mutable parallel collection yields a sequential
Log The operation takes time proportional to the loga- mutable collection which is backed by the same store updates to one
rithm of the collection size. ParHashSet/ParHashMap C C C collection will be visible in the other one.
L The operation is linear, that is it takes time propor- ParTrieMap eC eC eC
tional to the collection size. 3.6 Architecture of the Parallel Collections
- The operation is not supported. Library
3 Scala Parallel Collections 3.5 Parallel Collection Conversions Two core abstractions: Splitters and Combiners.
Splitter
3.1 Creating a Parallel Collection Every sequential collection can be converted to its parallel variant
Two ways to create a parallel collection: new and par. using the par method. Certain sequential collections have a direct trait Splitter[T] extends Iterator[T] {
parallel counterpart. For these collections the conversion is efficient def split: Seq[Splitter[T]]
3.2 Semantics it occurs in constant time, since both the sequential and the parallel }
Conceptually, Scalas parallel collections framework parallelizes an collection have the same data-structural representation (one
Combiner
operation on a parallel collection by recursively splitting a given exception is mutable hash maps and hash sets which are slightly
collection, applying an operation on each partition of the collection more expensive to convert the first time par is called, but subsequent
trait Combiner[Elem, To] extends Builder[Elem, To] {
in parallel, and re-combining all of the results that were completed invocations of par take constant time). It should be noted that for
def combine(other: Combiner[Elem, To]): Combiner[Elem, To]
in parallel. mutable collections, changes in the sequential collection are visible in
}
These concurrent, and out-of-order semantics of parallel collections its parallel counterpart if they share the underlying data-structure.
lead to the following two implications:
Copyright ⃝
c 2014 soulmachine
1. Side-effecting operations can lead to non-determinism Github: https://github.com/soulmachine/scala-cheat-sheet
Table 13: Sequential collections and their direct parallel coun- My blog: http://www.soulmachine.me
2. Non-associative operations lead to non-determinism terparts Last update: March 29, 2014

You might also like