Scala Reference Guide - DL
Scala Reference Guide - DL
Operators
x op y is x.op(y) infix notation where op can be +, -, *, /, %
x op is x.op( ) postfix notation
x == y compares two objects (calls equals method)
There is no ++, -- in Scala
Symbols
; optional end of line
-> returns a two element tuple for a key, value pair
<- assign to in a for comprehension
=> used in function literals to separate arguments from the function body
:: cons operator
// single-line comment
/*…*/ multiline comment
Relational Operators
|| or
&& and
! not
Comparison
== equals
< less than
> greater than
<= less than or equal to
>= greater than or equal to
Variables
var creates a mutable variable
var myVar:Int creates a mutable integer variable
val creates an immutable variable
val myVal:String creates an immutable String variable ( or val myVal = “Monday”)
Data Types
Byte
Short
Int
Long
Float
Double
Boolean
String
Char
Unit
Null
Nothing
Any
AnyRef
Data Structures
(1,2,3) tuple literal
var(a,b,c) = (1,2,3) tuple unpacking via pattern matching
var xs = List(1,2,3) creates an immutable list called xs
xs(0) access the element at location zero, indexing
4::List(3,2,1) adds 4 to the front of the list creating List(4,3,2,1)
1 to 10 range of numbers from 1 to 10 inclusive
1 until 10 range of numbers from 1 to 9, excludes upper bound
val list = List.range(1,11) creates a List of values excluding the upper bounds
Loops
while(expr) {…} execute a body of code while the expr is true
do{…} while(expr) execute a body of code at least once, continue while expr is true
for(x <- myList) println(x) print all values of x from the List called myList
for(x <- myList if x%2 == 0) yield x*10 for comprehension
for(x <- 1 to 10) {…}
Pattern Matching
val x = r match {
case ‘0’ => … //match a value
case ch if someProperty(ch) => … //add a guard to the match criteria
case e: Employee => … //match runtime type
case (x,y) => … //destructures pairs
case Some(v) => … //case classes have extractors
case 0 :: tail => … //infix notation for extractors yielding a pair
case _ => … //default case
Escape Sequences
\b backspace
\t tab
\n newline
\r carriage return
\” double quote
\’ single quote
\\ backslash