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.