A Scala cheat sheet (reference page)

Summary: This document is a Scala cheat sheet (reference page), in HTML format. (Update: This is a little dated, but I hope it’s still helpful.)

This page is a work in progress, but as I've been learning Scala, I've been creating all sorts of little notes, and I'm now trying to organize them into this Scala cheat sheet. Many of the initial notes were based on the excellent book, Programming in Scala (Odersky, Spoon, and Venners).

(Here's a link to my companion document, a Scala cheat sheet in PDF format.)

Introduction

Scala:

  • is a high-level language
  • is statically typed
  • is concise
  • supports the object-oriented programming paradigm
  • supports the functional programming paradigm
  • supports a sophisticated type inference system
  • has traits, which are like mixins
  • has an Actors API, which is based on the Actors concurrency model built into Erlang
  • uniform access principle
  • more ...

Functional programming

Two main ideas in functional programming:

  1. Functions are first-class values. Same status as something like an integer or a string.
  2. Operations of a program should map input values to output values rather than change data in place ...

Other notes:

  • function types are classes ... functions are first-class values
  • every value is an object and every operation is a method call
  • Immutable data structures are one of the cornerstones of functional programming
  • Methods should not have any side effects, they should take arguments and return results ... "referentially transparent" ... a function application is characterized only by its result.

Note from Programming Scala:

  • Prefer "val" (try to program without "var", prefer immutable objects)
  • Functions should not have side effects
  • "Telltale sign of a function with side effects is that its result type is Unit"

Scala variables

Two types of Scala variables:

  1. var - a variable, can be changed
  2. val - also a "variable", but can't be changed, like a Java "final" variable

Examples:

// a variable (mutable)
var x = 1
x = 2

// an immutable field (can't change the reference)
val x = 1
x = 2      // this causes an error

Implicit and explicit types

Notice right away that types can be implicit:

// an Int
val x = 1

// a String
val s = "Hello, world"

Or you can specify them explicitly:

val x: Int = 5

Scala loops (while, do, for)

Scala loop constructs:

  • while
  • do
  • for
  • foreach
  • true and false keywords

Scala while loop examples

Some simple Scala while loop examples:

var i = 0
while (i < array.length) {
  println(array(i)
  i += 1
}

Note that i++ and i don't work in Scala because it is a true OO language.

while (hungry) {
  println("Me hungry")
  hungry = getHungerStatus
}

Scala for loop examples

Some simple Scala for loop examples:

Say "for arg in args":

for (arg <- args) println(arg)

For loop with the "x to y" syntax:

// "x to y" syntax
for (i <- 0 to 5) println(i)

// "x to y by" syntax
for (i <- 0 to 10 by 2) println(i)

TODO Much more to document about for loops, including "if" syntax like this:

for (
  file <- files
  if file.isFile
  if file.getName.endsWith(".txt")
) doSomething(file)

(The book "Programming in Scala" has excellent examples of this.)

foreach examples

Some simple Scala foreach loop examples:

// function literal - body is "println(arg)"
args.foreach(arg => println(arg))

// shorter
args.foreach(println(_))

// even shorter - if function literal consists of one
// statement that takes a single argument, you can do this:
args.foreach(println)

Scala scripts and command line arguments

Use the "args" array to access command line arguments in Scala, so elements are arg(0), arg(1), etc.

println("Hello, " + args(0))

or this:

println(args.toList)

Run a Scala script like this:

scala hello.scala

Can also access command line args like these examples:

args.foreach(arg => println(arg))

// shorter
args.foreach(println(_))

// even shorter - if function literal consists of one
// statement that takes a single argument, you can do this:
args.foreach(println)

Scala control structures

Scala if/then control structures:

if (a == b) doSomething()

if (a == b) doSomething() else doSomethingElse()

if (a == b) {
  doSomething()
} else {
  doSomethingElse()
}

Scala 'if' and 'else if' syntax examples:

if (test) // do something
else if (test) // do something
else if (test) // do something
else  // do something

Scala functions

Scala functions are created with the "def" keyword:

// define a function
def hello():Unit = {
  println("Hello, world")
}

// call the function
hello

Can simplify the signature:

def hello() {
  println("Hello, world")
}

More simplified:

def hello {
  println("Hello, world")
}

Even more simplified:

def hello = println("Hello, world")

With function parameters and a return value:

def max(x: Int, y: Int): Int = {
  if (x > y) x
  else y
}

A shorter version of that same function. Notice the implicit return and return type:

def max(x: Int, y: Int) = if (x > y) x else y

Defining function literals

The basic function literal format:

// function literal format. 
(x: Int, y: Int) => x + y

Syntax:

  • function parameters are in parentheses
  • right arrow
  • function body to the right of the right arrow

(TODO: More/better examples here.)

Variable-length argument lists

Use the "*" syntax, like this:

def printAll(args: String*) = args.foreach(println)
printAll("a", "b", "c")

Passing Scala functions as function arguments

A simple example of passing a Scala function as a function argument:

scala> def foo = println("Hello")
foo: Unit

scala> def bar(u:Unit) = u
bar: (u: Unit)Unit

scala> bar(foo)
Hello

(TODO: More/better examples here.)

Scala functions - Summary

Summary:

  • Several different formats (but they are consistent, and based on need)
  • Value of last statement is return value
  • Must specify argument types
  • Specifying return type is optional
  • Don't forget the equal sign in the definition
  • Can pass functions around like variables
  • A return type of Unit indicates the function doesn't return anything interesting

(TODO: Add "currying")

Common Scala data structures and types

Array, Map, List, tuples, and more ...

Array

val names = Array("Fred", "Barney", "Betty")
val names = Array.apply("Fred", "Barney", "Betty")

Map

var info = Map("first_name"->"Al", "last_name"->"Alexander")
info += ("state"->"Alaska")

Scala List

val names = List("Fred", "Barney", "Betty")
// "cons" - prepend elements
val moreNames = "Wilma" :: names

"::" is a a right operand, because the method name ends in ":"

Scala tuples

Tuples can contain different types of elements.

val things = (100, "Foo")
println(things._1)
println(things._2)

Scala types

Some basic Scala types. All are in package 'scala' except for String, which is in 'java.lang'.

Byte
Short
Int
Long

Char
String

Float
Double

Boolean

Rich wrapper classes:

Byte     scala.runtime.RichByte
Short    scala.runtime.RichShort
Int      scala.runtime.RichInt
Long     scala.runtime.RichLong

Char     scala.runtime.RichChar
String   scala.collection.immutable.String

Float    scala.runtime.RichFloat
Double   scala.runtime.RichDouble

Boolean  scala.runtime.RichBoolean

Scala classes and objects

Scala class and object syntax:

class Person {
}

Class variables:

class Person {
  var firstName
}
var p = new Person
p.firstName = "Al"

Another class definition:

class Person {
  var name = ""
  def hello = println("Hello")
  def hello1() = println("Hello 1")
}
var p = new Person
p.name = "Alvin Alexander"

println(p.name)
p.hello
p.hello1

Class definition with constructor:

class Person (theName: String) {
  val name = theName
  // this is printed from the constructor method
  println("Hello " + name)
}
var p = new Person("Al Alexander")

A class with "extends" and "with" syntax:

class Bird extends Animal with Wings {
 ...
 ...
}

TODO: Much more here, including "object" and "trait" compared to "class".

Scala class hierarchy

TODO: Discuss Unit, Any, and more here. (A nice Scala type hierarchy here.)

Scala try, catch, exception syntax

Similar to Java:

try {
  doSomething
} catch {
  case ex: FileNotFoundException => println(ex)
  case ex: IOException => // handle it
}

Scala traits (mixins)

Like Ruby "mixins" ...

You can do anything in a trait definition that you can do in a class definition with two exceptions:

  1. A trait cannot have any class parameters.
  2. In traits, "super" calls are dynamically bound.

TODO: Examples needed here ... Joel Abrahamsson has a good traits tutorial.

Importing Java classes

Examples of how to import Java classes into Scala code:

// import one class
import java.io.File

// import every class in a package
import java.io._

// import multiple classes from a package (version 1)
import java.io.{File, IOException, FileNotFoundException}

// import multiple classes from a package (version 2)
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException

// create an alias to a class you import
import java.io.{File => JFile}

After importing the Java File class you can use it like this:

f = new File("foo.txt")

Scala underscore use

Similar to an early O'Reilly example of the underscore use:

object Under {
  def main(args: Array[String]) = {
    args.foreach(printf("%s ", _))
  }
}

Third example from the O'Reilly book, Programming Scala:

// pass args from the command line
object Upper {
  def main(args: Array[String]) = {
    args.map(_.toUpperCase).foreach(printf("%s ", _))
    println("")
  }
}

Underscore use in a function literal:

(s:String) => s.toUpperCase

Can shorten this to:

_.toUpperCase

Scala Actors and messaging

This section is TBD, I haven't had much chance to use the Actors API.

Scala cheat sheet - TODO items

  • apply method
  • update method
  • companion object
  • match and case