Mathjax javascript librry setup

# Introduction

This cheat sheet originated from Coursera course Functional Programming in Scala It was originally created by Laurent Poulain, and then updated by the course presenters.

You can get the original markdown file by clicking the “Edit” button on this file on GitHub:
https://github.com/lrytz/progfun-wiki/blob/gh-pages/CheatSheet.md
You can submit a pull request directly from there without checking out the git repository to your local machine.

# Basic Scala

## Evaluation Rules

• Call by value: evaluates the function arguments before calling the function
• Call by name: evaluates the function first, and then evaluates the arguments if need be

## Higher order functions

These are functions that take a function as a parameter or return functions.

## Currying

Converting a function with multiple arguments into a function with a single argument that returns another function.

## Classes

this references the current object, assert(<condition>) issues AssertionError if condition is not met. See scala.Predef for require, assume and assert.

## Operators

myObject myMethod 1 is the same as calling myObject.myMethod(1)

Operator (i.e. function) names can be alphanumeric, symbolic (e.g. x1, *, +?%&, vector_++, counter_=)

The precedence of an operator is determined by its first character, with the following increasing order of priority:

The associativity of an operator is determined by its last character: Right-associative if ending with :, Left-associative otherwise.

Note that assignment operators have lowest precedence. (Read Java Language Specification 2.9 sections 6.12.3, 6.12.4 for more info)

## Class hierarchies

To create an runnable application in Scala:

## Class Organization

• Classes and objects are organized in packages (package myPackage).

• They can be referenced through import statements (import myPackage.MyClass, import myPackage._, import myPackage.{MyClass1, MyClass2}, import myPackage.{MyClass1 => A})

• They can also be directly referenced in the code with the fully qualified name (new myPackage.MyClass1)

• All members of packages java and java.lang as well as all members of the object scala.Predef are automatically imported.

• Traits are similar to Java interfaces, except they can have non-abstract members:

trait Planar { ... }
class Square extends Shape with Planar
• General object hierarchy:

• scala.Any base type of all types. Has methods hashCode and toString that can be overloaded
• scala.AnyVal base type of all primitive types. (scala.Double, scala.Float, etc.)
• scala.AnyRef base type of all reference types. (alias of java.lang.Object, supertype of java.lang.String, scala.List, any user-defined class)
• scala.Null is a subtype of any scala.AnyRef (null is the only instance of type Null), and scala.Nothing is a subtype of any other type without any instance.

## Type Parameters

Similar to C++ templates or Java generics. These can apply to classes, traits or functions.

## Variance

Given A <: B

If C[A] <: C[B], C is covariant

If C[A] >: C[B], C is contravariant

Otherwise C is nonvariant

class C[+A] { ... } // C is covariant
class C[-A] { ... } // C is contravariant
class C[A]  { ... } // C is nonvariant

For a function, if A2 <: A1 and B1 <: B2, then A1 => B1 <: A2 => B2.

Functions must be contravariant in their argument types and covariant in their result types, e.g.

Find out more about variance in lecture 4.4 and lecture 4.5

# Pattern Matching

Pattern matching is used for decomposing data structures:

Here are a few example patterns

The last example shows that every pattern consists of sub-patterns: it only matches lists with at least one element, where that element is a pair. x and y are again patterns that could match only specific types.

## Options

Pattern matching can also be used for Option values. Some functions (like Map.get) return a value of type Option[T] which is either a value of type Some[T] or the value None:

Most of the times when you write a pattern match on an option value, the same expression can be written more concisely using combinator methods of the Option class. For example, the function getMapValue can be written as follows:

## Pattern Matching in Anonymous Functions

Pattern matches are also used quite often in anonymous functions:

val pairs: List[(Char, Int)] = ('a', 2) :: ('b', 3) :: Nil
val chars: List[Char] = pairs.map(p => p match {
case (ch, num) => ch
})

Instead of p => p match { case ... }, you can simply write {case ...}, so the above example becomes more concise:

val chars: List[Char] = pairs map {
case (ch, num) => ch
}

# Collections

Scala defines several collection classes:

## Base Classes

• Iterable (collections you can iterate on)
• Seq (ordered sequences)
• Set
• Map (lookup data structure)

## Immutable Collections

• List (linked list, provides fast sequential access)
• Stream (same as List, except that the tail is evaluated only on demand)
• Vector (array-like type, implemented as tree of blocks, provides fast random access)
• Range (ordered sequence of integers with equal spacing)
• String (Java type, implicitly converted to a character sequence, so you can treat every string like a Seq[Char])
• Map (collection that maps keys to values)
• Set (collection without duplicate elements)

## Mutable Collections

• Array (Scala arrays are native JVM arrays at runtime, therefore they are very performant)
• Scala also has mutable maps and sets; these should only be used if there are performance issues with immutable types

# Ordering

There is already a class in the standard library that represents orderings: scala.math.Ordering[T] which contains comparison functions such as lt() and gt() for standard types. Types with a single natural ordering should inherit from the trait scala.math.Ordered[T].

# For-Comprehensions

A for-comprehension is syntactic sugar for map, flatMap and filter operations on collections.

The general form is for (s) yield e

• s is a sequence of generators and filters
• p <- e is a generator
• if f is a filter
• If there are several generators (equivalent of a nested loop), the last generator varies faster than the first
• You can use { s } instead of ( s ) if you want to use multiple lines without requiring semicolons
• e is an element of the resulting collection

## Translation Rules

A for-expression looks like a traditional for loop but works differently internally

for (x <- e1) yield e2 is translated to e1.map(x => e2)

for (x <- e1 if f) yield e2 is translated to for (x <- e1.filter(x => f)) yield e2

for (x <- e1; y <- e2) yield e3 is translated to e1.flatMap(x => for (y <- e2) yield e3)

This means you can use a for-comprehension for your own type, as long as you define map, flatMap and filter.

For more, see lecture 6.5.

## Example 2

ScalaDoc is Scala’s version of JavaDoc … it uses a structured set of comments to document Scala code.

• The ScalsDoc section of the Scala Style Guide is a good place to start for basic templates for using ScalaDoc.
• The ScalaDoc tags and annotations are similar to those of Javadoc
• The ScalaDoc wiki syntax is used to format the documentation. Avoid using HTML (which gets used in JavaDoc)
• Use the sbt command doc to generate both ScalaDoc and JavaDoc for the project. The generated documentation is placed at:
• <project>/target/scala-2.11/api

### Parameter Tags

• @param <name> <body> Documents a specific value parameter of a method or class constructor. One @param tag allowed per value parameter in comment for method, constructor or class (documents primary constructor). argument must correspond to an existing value parameter.
• @tparam <name> <body> Documents a specific type parameter of a method, class, trait or abstract type. One @tparam tag allowed per type parameter in comment for method, class, trait or abstract type. argument must correspond to an existing type parameter.
• @return <body> Documents the return value of a method. One @return tag allowed in comment for method.
• @throws <name> <body> Documents an exception type that may be thrown by a method or class constructor. Any number of @throws tags allowed in comment for method, constructor or class (documents primary constructor), no duplicate names allowed.

### Usage Tags

• @see <body> Points to other sources of information such as external documentation or related entities in the documentation. Any number of @see tags allowed in any comment.
• @note <body> Documents pre- and post-conditions as well as other notable requirements or restrictions. Any number of @note tags allowed in any comment.
• @example <body> Provides example code and related descriptions. Any number of @example tags allowed in any comment.
• @usecase <simple definition> In case the method definition is too complex, you can add simple aliasing definition as a usecase. It will create another entry in the scaladoc page as if the actually existed. The description for the newly created entry is the same as the one for the current symbol, just that it’s preceded by [use case] to signal it’s not a real entry. An example can be seen in the ++ method of scala.collections.immutable.Set. Inventory Tags
• @author <author> Attributes an entity to one author. Any number of @author tags allowed in any comment: if multiple authors contributed, use one tag per author.
• @version <version> The version of the system or API that a class, trait, object or package is part of. One @version tag allowed in comments for class, trait, object or package.
• @since <version> The version of the system or API that an entity was first defined in. One @since tag allowed in any comment. This tag should only be used in conjunction with a @version tag in an enclosing class, trait, object or package.

### Other Tags

• @todo <body> Documents unimplemented features in an entity. Any number of @todo tags allowed in any comment.

### Inline elements

• Italic ''text''
• Bold '''text'''
• Underline __text__
• Monospace text
• Superscript ^text^
• Subscript ,,text,,
• Entity links [[scala.collection.Seq]] becomes a link to the corresponding entity like Seq. The entity must be linked using fully-qualified names (scala.collection.Seq instead of Seq); this requirement may be relaxed in a future release.
• External links [[http://scala-lang.org Scala web site]] becomes Scala web site. The URL part must start with a scheme name (like http:) and must not contain white space. The name part (Scala web site) is optional.

## Block elements

• Paragraphs a blank line starts a new paragraph. Note that a “blank line” may contain a left margin * delimiter, as described above.
• Code blocks enclose between }. See rule above for determining left margin.
• Headings =heading= defines a heading. Lower-level heading are obtained by using more = signs, like ===sub-heading===. A heading must be define on its own line.
• List block A list block is a sequence of list items of the same style and level, uninterrupted by other block elements. Unordered list item $- item becomes a list item ($ signifies the left margin of a line (it doesn’t appear in the code), note the space between the left margin and the dash). More leading space characters are allowed between the left margin and the dash: list items with the same number of leading spaces are at the same level, more space creates sub-levels.
• Ordered list item uses similar rules to the unordered item, but replace dash by one of 1., I., i., A. or a. for various numbering styles.