Scala Flashcards
var x = 5
variable
val x = 5
constant
x = 5
constant, bad form!
var x: Double = 5
explicit type
def f(x: Int) = { x*x }
define function
def f(x: Int) { x*x }
error: without “=” it’s a Unix-returning procedure
def f(x: Any) = println(x)
Any is the root of the Scala class hierarchy. This function can take anything for parameter.
def f(x) = println(x)
Syntax error: must have a type for every arg.
type R = Double
type alias
call by? def f(x: R)
call-by-value
call by? def f(x: => R)
call-by-name (lazy parameters)
(x:R) => x*x
anonymous function
(1 to 5).map(*2)
or
(1 to 5).reduceLeft(+_)
anonymous function - underscore is positionally matched argument
(1 to 5).map( x => x*x )
anonymous function: to use an argument twice, you have to name the variable
(1 to 5).map(2)
or
(1 to 5).map(2)
anonymous function bound infix method. Use 2*_ instead.
(1 to 5).map {val x=_*2; println(x); x}
anonymous function - block style returns last expression
(1 to 5) filter {%2 == 2} map {*2}
anonymous function - pipeline style.
def compose(g:R=>R, h:R=>R) = (x:R) => g(h(x)) val f = compose({_*2),{_-1})
anonymous function - to pass in multiple blocks, need outer parenthesis
val zscore =
(mean:R, sd:R) =>
(x:R) =>
(x-mean)/sd
currying
def zscore(mean:R, sd:R) =
(x:R) =>
(x-mean)/sd
currying
def zscore(mean:R, sd:R)(x:R) = (x-mean)/sd
currying (syntax sugar)
val normer = zscore(7, 0.4)_
need trailing underscore to get the partial, only for the sugar version
def mapmakeT(seq: List[T]) = seq.map(g)
generic type
5.+(3); 5 + 3
1 to 5) map (_*2
infix sugar
def sum(args: Int*) = args.reduceLeft(+)
varargs
import scala.collection._
wildcard import
import scala.collection.Vector
import scala.collection.{Vector,Sequence}
selective import
import scala.collection.{Vector => Vec28}
renaming import
(1,2,3)
tuple literal (Tuple3)
var (x,y,z) = (1,2,3)
destructuring bind: tuple unpacking via pattern matching
var xs = List(1,2,3)
list (immutable)
var xs = List(1,2,3) xs(2)
parenthesis indexing
1 :: List(2,3)
cons
Byte
8 bit signed value
Short
16 bit signed value
Int
32 bit signed value
Long
64 bit signed value
Float
32 bit floating point
Double
64 bit floating point
Unit
Corresponds to no value
Null
null or empty reference
Nothing
The subtype of every other type, includes no values
Any
Supertype of any type. Any object is of type Any.
AnyRef
The supertype of any reference type