Essential Essential Scala
Essential Essential Scala
Essential Scala
Dave Gurnell, @davegurnell
underscore
Prologue
in which we learn what were in for
Essential Me
Dave Gurnell
[email protected]
6 years Scala
10 years functional programming
Essential Overview
Scala is
Statically typed
Object oriented
Functional
Essential Overview
Creating data
Processing data
Sequencing computation
Abstractions on abstractions
Essential Context
???
Operator Syntax
1 is an object
+ is a method
2 is an argument
Operator Syntax
1 + 1 is 1.+(2)
a b c is a.b(c)
a b c d is a.b(c).d
An object
is a value
Defining Fields
Syntax for defining fields
Example
expression match {
case pattern1 => expression1
case pattern2 => expression2
// ...
}
Pattern Matching
case class Person(f: String, l: String)
object Name {
// body goes here
}
A has an X and a Y
trait Name {
// body goes here
}
A is a B or C
trait A
case class B(...) extends A
case class C(...) extends A
Make it so!
Destructuring Data
trait A {
def foo: X
}
trait A {
def myMethod = this match {
case B(...) => ...
case C(...) => ...
}
}
Math tip:
the area of a rectangle is width * height
the area of a circle is pi * radius 2
A is an X or a Y
trait IntList
case object Empty extends IntList
case class Cell(head: Int, tail: IntList)
extends IntList
Recursive Data
Polymorphic Pattern
methods matching
Adding a type
Adding an
operation
Structural Recursion
Polymorphic Pattern
methods matching
Add Change
Adding a type
new code existing code
Adding an Change Add
operation existing code new code
Summary
Summary
val func =
(a: Int, b: Int) =>
(a + b) / 2
func(1, 3) // returns 2
Functions
A complete example
Type
plus2(10) // returns 12
Higher Order Functions
We can write methods and functions
that accept and return other functions!
func(10) // returns 42
Higher Order Functions
We can write methods and functions
that accept and return other functions!
both(10) // returns 22
Exercises
Exercises
trait Name[A] {
// body goes here
}
A concrete example
trait LinkedList[A] {
def map[B](item: A => B): LinkedList[B]
}
trait LinkedList[A] {
def flatMap[B](
func: A => LinkedList[B]
): LinkedList[B]
}
Summary
Scala is
Statically typed
Object oriented
Functional
Essential Scala
Creating data
objects and classes
Processing data
algebraic datatypes, case classes, traits
Sequencing computation
polymorphism, pattern matching, structural recursion
Abstractions on abstractions
classes, traits, functions, generics, etc
Essential Scala
Thanks!
underscore