1. e
Scala
Programming Language
Christopher League
LIU Brooklyn
February
2. Prehistory
Martin Odersky receives Ph.D. from
Niklaus Wirth at ETH Zürich.
Odersky and Phil Wadler team up to design
Pizza, a functional language that targets
Java Virtual Machine.
Propose Generic Java, with Gilad Bracha
and David Stoutamire
3. History
Sun proposes to incorporate Generic Java
Odersky begins design of Scala at EPFL
GJ compiler released as Java .
First public Scala release
Scala version release
Typesafe Inc. founded to support and
promote Scala.
4. Who uses Scala?
AppJet Office Depot
Ebay SAIC
Foursquare Siemens
GridGain Sony
Guardian Sygneca
LinkedIn atcham
Managed Gaming Twitter
Nature WattzOn
Novell Xebia
Novus Partners Xerox
OPower ...
7. Scala is... concise
Typical Java class definition
class MyClass {
private int index;
private String name;
public MyClass(int index, String name) {
this.index = index;
this.name = name;
}
}
Equivalent Scala class definition
class MyClass(index: Int, name: String)
8. Scala is... high-level
Java: Does a string have an uppercase character?
boolean nameHasUpperCase = false;
for (int i = 0; i < name.length(); ++i) {
if (Character.isUpperCase(name.charAt(i))) {
nameHasUpperCase = true;
break;
}
}
Equivalent Scala:
val nameHasUpperCase = name.exists(_.isUpper)
10. Agenda
. Introduction to Scala
. Object-oriented programming
. Objects, classes, and traits
. Collections hierarchy
. Functional programming
. Immutability
. Higher-order functions
. Algebraic data types
. Concurrency
. Summary and resources
11. Objects and classes
In Java and C++, classes...
. are a template for creating new objects dynamically
. define the methods and fields of those objects
. provide a namespace for static methods and
fields, unconnected to a particular object
In Scala,
Classes are responsible only for and .
For , we define a singleton object as a container
for static members.
12. Example
class ChecksumAccumulator {
private var sum = 0
def add(b: Byte) { sum += b }
def checksum(): Int = ˜(sum & 0xFF) + 1
}
object ChecksumAccumulator {
private val cache = Map[String, Int]()
def calculate(s: String): Int =
if (cache.contains(s)) cache(s)
else {
val acc = new ChecksumAccumulator
for (c <- s) acc.add(c.toByte)
val cs = acc.checksum()
cache += (s -> cs)
cs
}
13. Other notable features
Identifiers declared as either val (immutable value)
or var (mutable variable)
Methods introduced by def
Array/map/function syntax are unified: cache(s)
Instantiation of generic types: Map[String, Int]
if/else returns a value
Last expression of a block is returned, as long as
method body preceded by ‘=’
Very general loop syntax: for(x <- xs) . . .
(More on that later...)
14. Immutable object example
class Rational(n: Int, d: Int) { // main constructor
require(d != 0) // or else IllegalArgumentException
private val g = gcd(n.abs, d.abs)
val numer = n / g
val denom = d / g
def this(n: Int) = this(n, 1) // auxiliary c’tor
def add(that: Rational): Rational =
new Rational
(numer * that.denom + that.numer * denom,
denom * that.denom)
override def toString = numer + ”/” + denom
private def gcd(a: Int, b: Int): Int =
if (b == 0) a else gcd(b, a % b)
}
15. Traits
A trait encapsulates method and field definitions,
which can then be reused by mixing them into
classes.
A class can mix in any number of traits, defining
stackable modifications.
16. Traits example
class Animal(val name: String) {
override def toString = name
}
trait Philosophical {
def think {
println(this + ”: ” +
”I consume memory, therefore I am.”)
}
}
class Squid extends Animal(”Søren”) with Philosophical
trait HasLegs {
def legCount: Int
def jump {
println(this + ”: How high?”)
}
}
17. Traits example
class Frog(name: String) extends Animal(name)
with HasLegs with Philosophical {
override def think {
println(this + ”: It ain’t easy being green.”)
}
def legCount = 4
}
trait Biped extends HasLegs {
def legCount = 2
}
class Human(name: String) extends Animal(name)
with Biped with Philosophical
18. Traits example
scala> val s = new Squid
s: Squid = Søren
scala> val f = new Frog(”Kermit”)
f: Frog = Kermit
scala> val h = new Human(”Alice”)
h: Human = Alice
scala> s.think
Søren: I consume memory, therefore I am.
scala> f.think
Kermit: It aint easy being green.
scala> h.legCount
res3: Int = 2
scala> f.legCount
res4: Int = 4
scala> s.legCount
error: value legCount is not a member of Squid
21. Agenda
. Introduction to Scala
. Object-oriented programming
. Objects, classes, and traits
. Collections hierarchy
. Functional programming
. Immutability
. Higher-order functions
. Algebraic data types
. Concurrency
. Summary and resources
22. Immutability
Identifiers declared as either val (immutable value)
or var (mutable variable)
scala.collection.immutable vs.
scala.collection.mutable
scala> import scala.collection.mutable.{Set => MSet}
scala> import scala.collection.immutable.Set
scala> val s1 = MSet(2,6,7,9)
scala> val s2 = Set(3,4,7,8)
scala> s1 += 5
res9: s1.type = Set(9, 2, 6, 7, 5)
scala> s1 contains 5
res10: Boolean = true
scala> s2 += 5
error: reassignment to val
23. Why prefer immutability?
Referential transparency — easier for compilers
and people to reason about code if f(x) always
equals f(x)
Concurrency — multiple threads updating a single
variable or data structure can corrupt it. Fewer
updates make it easier to prevent corruption.
24. Higher-order functions
Function values can be passed to other functions,
stored in data structures. Syntax of function value:
{ (x: Int) => x * x }
{ x => x * 2 } // if type can be inferred
{ _ * 2 } // if parameter used just once
Example from before: name.exists( .isUpper)
Define your own control structures!
def unless(cond: Boolean)(block: =>Unit) =
if(!cond) block
unless(3 < 1) { println(”Huh.”) }
25. e flexible ‘for’ comprehension
scala> for(i <- 0 to 3; j <- i+1 to 4) yield (i,j)
scala.collection.immutable.IndexedSeq[(Int, Int)] =
Vector((0,1), (0,2), (0,3), (0,4),
(1,2), (1,3), (1,4),
(2,3), (2,4),
(3,4))
‘for’ is based entirely on higher-order functions:
(0 to 3).flatMap(i =>
(i+1 to 4).map(j =>
(i,j)))
// where:
flatMap[B](A => TraversableOnce[B]): Seq[B]
map[B](A => B): Seq[B]
26. Algebraic data types
Based on case classes in Scala:
abstract class Tree[A]
case class Leaf[A](value: A) extends Tree[A]
case class Branch[A](
left: Tree[A], right: Tree[A]
) extends Tree[A]
You can construct objects without new
All parameters become immutable fields
Compiler generates sensible toString, equals,
and copy methods.
Live-coding binary tree operations
27. Agenda
. Introduction to Scala
. Object-oriented programming
. Objects, classes, and traits
. Collections hierarchy
. Functional programming
. Immutability
. Higher-order functions
. Algebraic data types
. Concurrency
. Summary and resources
30. Scala actors
Actors are objects that send/receive messages.
a ! m sends message m to actor a, and returns
immediately (fire and forget).
System serializes message receives within actor.
react does not block thread, but also does not
return.
Can arrange computations to follow react using
loop, andThen.
31. Scala actor messaging
import scala.actors.Actor._
case object Incr
case object Get
val counter = actor {
var n = 0
loop { // repeatedly wait for a message
react { // (but don’t block thread)
case Incr => n += 1; println(n)
case Get => sender ! n
}
}
}
counter ! Incr // fire and forget; eventually
counter ! Incr // prints ’1’ then ’2’
32. Future power people
scala> counter ! Incr
scala> counter ! Incr
3
4
scala> val f = counter !! Get
f: z.Future[Any] = <function0>
scala> f.foreach { case x: Int =>
println(”Square is ” + x*x) }
Square is 16
33. ‘For’ the future
Because Future implements standard collection
methods like flatMap, you can sequence
asynchronous computations with ‘for’ syntax:
for(r1 <- act1 !! SomeOperation(x1,x2);
r2 <- act2 !! AnotherOperation(r1,y1,y2))
{
storeResult(r2)
}