Unleash Your Potential - Namagunga Girls Coding Club
All about scala
1. ALL* ABOUT SCALA
*ALL I COULD FIT IN 90 MINUTES PRESENTATION,
IN FACT THERE IS MUCH MORE TO SCALA…
Yardena Meymann
January 10, 2012
http://www.meetup.com/ILTechTalks/
1 of 99 Created on 10/01/2012
2. NAVIGATION
– Background
– Scala basics
– OOP in Scala
– FP in Scala
– Concurrency
– Tools
– Resources
2 of 99 Created on 10/01/2012
3. IT DOES NOT HAVE TO BE JAVA
it is tastier when you
Scala Java
Groovy
mix them!
Groovy Java
Scala Compiler
Compiler Compiler
Bytecode Bytecode Bytecode
Java Virtual Machine
3 of 99 Created on 10/01/2012
4. WHAT IS SCALA
– Object oriented and functional
– Statically typed - advanced type system
– Compiled to JVM bytecode
but also to CLR, and to JavaScript (in progress);
works with Dalvik
– High performance
– Very good interoperability with Java
– Support for modularity and extensibility
DSL friendly
4 of 99 Created on 10/01/2012
5. JAVA AND SCALA TIMELINE
lawsuit
2001
Java 7
(Dolphin)
2009 2011
€2.3 million
2011 2011
2.7 2008 2.8 2010
2.3 2007 2.9 2011
5 of 99 Created on 10/01/2012
6. THEN AND NOW
“If I were to pick a
language to use
today other than
Java, it would be
Scala”
James Gosling
6 of 99 Created on 10/01/2012
7. TOOLS
– IDE:
• built-in REPL, Scala IDE (based on Eclipse), IntelliJ and NetBeans plug-ins, ENSIME
scala>
– Tools
• https://wiki.scala-lang.org/display/SW/Tools+and+Libraries
• integration modules for almost every popular Java framework
7 of 99 Created on 10/01/2012
16. HELLO SCALA
package com.hp.scala
object HelloScala {
def main(args: Array[String]) {
println(“Hello Scala”)
}
}
package com.hp.scala;
public class object HelloScala {
public static void def main(String[] args: Array[String]) {
System.out.println(“Hello Scala”);
}
}
16 of 99 Created on 10/01/2012
17. HELLO SCALA - VARIABLES
object HelloScala {
def main(args: Array[String]) {
val msg = “Hello Scala”
println(msg)
}
}
17 of 99 Created on 10/01/2012
18. HELLO SCALA – TYPE INFERENCE
object HelloScala {
def main(args: Array[String]) {
val msg = “Hello Scala”
println(msg)
}
}
18 of 99 Created on 10/01/2012
19. VAL VS. VAR
object HelloScala {
def main(args: Array[String]) {
val msg = “Hello Scala”
println(msg)
msg = “Goodbye Java”
println(msg)
}
}
19 of 99 Created on 10/01/2012
20. VAL VS. VAR
object HelloScala {
def main(args: Array[String]) {
var msg = “Hello Scala”
println(msg)
msg = “Goodbye Java”
println(msg)
}
}
20 of 99 Created on 10/01/2012
21. METHODS (VERBOSE)
object HelloScala {
def main(args: Array[String]) {
println(hello(“Scala”))
}
def hello(who: String): String = {
return “Hello ” + who
}
}
21 of 99 Created on 10/01/2012
22. METHODS (SHORTER)
object HelloScala {
def main(args: Array[String]) {
println(hello(“Scala”))
}
def hello(who: String): String = {
“Hello ” + who
}
}
22 of 99 Created on 10/01/2012
23. METHODS (SHORTER YET)
object HelloScala {
def main(args: Array[String]) {
println(hello(“Scala”))
}
def hello(who: String) = {
“Hello ” + who
}
}
23 of 99 Created on 10/01/2012
24. METHODS (SHORT)
object HelloScala {
def main(args: Array[String]) {
println(hello(“Scala”))
}
def hello(who: String) = “Hello ” + who
}
24 of 99 Created on 10/01/2012
25. ARRAY ACCESS
object HelloScala {
def main(args: Array[String]) {
println(hello(args(0))
//args(0) is a shortcut for args.apply(0)
}
def hello(who: String) = “Hello ” + who
}
25 of 99 Created on 10/01/2012
26. CONDITION
object HelloScala {
def main(args: Array[String]) {
if (!args.isEmpty) println(hello(args(0))
}
def hello(who: String) = “Hello ” + who
}
//isEmpty() method has no arguments, and therefore can be
invoked without the ()
26 of 99 Created on 10/01/2012
27. IF EXPRESSION, NOT STATEMENT
object HelloScala {
def main(args: Array[String]) {
println(hello(
if (args.isEmpty) “Anonymous” else args(0)))
}
def hello(who: String) = “Hello ” + who
}
27 of 99 Created on 10/01/2012
28. FUNCTION OBJECT
object HelloScala {
def main(args: Array[String]) { …
}
val hello = (who: String) => “Hello “ + who
// equivalent to
//val hello = new Function1[String, String] {
// def apply(who: String): String = “Hello “ + who
//}
}
28 of 99 Created on 10/01/2012
29. FOREACH
object HelloScala {
def main(args: Array[String]) {
args.foreach(arg => println(hello(arg)))
}
def hello…
}
//example of anonymous function object
29 of 99 Created on 10/01/2012
30. OPERATORS, INFIX SYNTAX
def hello(who: String) = “Hello ”.+(who)
//same as “Hello ” + who
//NOTE that this is an example, not a recommended coding style:
def main(args: Array[String]) {
Console println hello (if (args isEmpty) “Anonymous” else args apply 0)
}
30 of 99 Created on 10/01/2012
31. MATCH EXPRESSIONS
– Matching on values (Java’s switch)
val times = 1
times match {
case 1 => "one"
case 2 => "two"
case _ => "some other number"
}
– No fall-through!
– Matching with guards
n match {
case it if 0 until 5 contains it => "less than five"
case it if 5 until 10 contains it => "less than ten"
case _ => "a lot“
}
31 of 99 Created on 10/01/2012
32. EXCEPTIONS
– Throwing an exception looks the same as in Java
– You catch exceptions using the syntax:
– NOTE: All exceptions in Scala are runtime
32 of 99 Created on 10/01/2012
33. CREATING A SEQUENCE
–Array(1,2,3)
• Arrays are mutable
–List(3.14, 2.72, 1.62)
• Lists are by default immutable, singly-linked
• Nil is an empty list
–Map: val romanNumeral =
Map(1 ->"I", 2 -> "II", 3 -> "III", 4 -> "IV", 5 -> "V“ )
// x -> y creates a tuple (x,y)
33 of 99 Created on 10/01/2012
34. MAP VALUES – ANOTHER OPTION
–What if key is not in the Map?
–Map.get returns an Option:
• Some(value), value can be retrieved with get
• or None
–getOrElse method allows to specify default:
• treasureMap.getOrElse(1, “Oops”)
• treasureMap.getOrElse(4, “Oops”)
–Safe alternative to null-checks
34 of 99 Created on 10/01/2012
Scala
35. OPERATING WITH A SEQUENCE
– foreach(E=>Unit), – exists(E=>Boolean),
– filter(E=>Boolean), – remove(E=>Boolean),
– map(E=>X), – reverse,
– reduceLeft((E,E)=>E), – sort((E,E)=>Boolean),
– take(Int), – head,
– drop(Int), – tail,
– indexOf(E), – … more later
35 of 99 Created on 10/01/2012
36. RICH WRAPPERS
– A Range can be created: „a‟ to „z‟ or 1 until 10
– Scala compiler made an implicit conversion of Int to
scala.runtime.RichInt
• To check if conversion is available: implicitly[Int => RichInt]
(in REPL first import scala.runtime._)
• Alternatively: scalac –Xprint:typer
– Another Example:
• reg-exp
• "()?(d+)(.d*)?".r
36 of 99 Created on 10/01/2012
37. PLACEHOLDER
(1 to 10) filter ((i: Int) => i%2 == 0) mkString “,”
or equivalent shorter version:
… filter (i => i%2 == 0)
or yet shorter using placeholder:
… filter (_ %2 == 0)
(1 to 10).reduceLeft((acc: Int, i: Int) => acc + i)
or equivalent shorter version:
… reduceLeft((acc, i) => acc + i)
or yet shorter using placeholders:
… reduceLeft(_ + _)
37 of 99 Created on 10/01/2012
38. CLOSURES
–So far, function literals have referred only to
passed parameters
(x: Int) => x > 0
–You can, however, refer to variables defined
elsewhere
(x: Int) => x + more // how much more?
–more is a free variable, because the function
literal does not itself give a meaning to it.
–x variable, by contrast, is a bound variable.
38 of 99 Created on 10/01/2012
39. CLOSURES
The function value (the object) that’s created at
runtime from addMore function literal is called a
closure.
The name arises from the act of “closing” the function literal by
“capturing” the bindings of its free variables
39 of 99 Created on 10/01/2012
40. EXAMPLE
def tryWithLogging (s: => Unit) {
try {
s
} catch {
case ex: Exception => ex.printStackTrace()
}
}
val file = new File(“test.txt”)
tryWithLogging {
val writer = new PrintWriter(file)
writer.println(“this is a test”)
}
If you’re passing exactly one argument to a method, you can use curly
braces instead of parentheses to surround it.
40 of 99 Created on 10/01/2012
41. HELLO SCALA – FOR COMPREHENSION
object HelloScala {
def main(args: Array[String]) {
for (arg ← args) println(hello(arg)))
}
def hello…
}
41 of 99 Created on 10/01/2012
42. MORE ON FOR EXPRESSION
–map alternative – yield:
def scalaFiles =
for {
file (new java.io.File(".")).listFiles
if file.getName.endsWith(".scala")
} yield file
• When the for expression completes, the result will include
all of the yielded values contained in a single collection.
• The type of the resulting collection is based on the kind of
collections processed in the iteration clauses.
42 of 99 Created on 10/01/2012
43. SCALA HIERARCHY
– Nothing is the subtype of all other types.
• It has no instances.
• It is used primarily for defining other types in a
type-safe way, such as the
special List subtype Nil.
– Null has one instance, null,
corresponding to the runtime’s concept
of null.
– FunctionN[-T1, -T2, …, -TN, +R] a
function that takes N arguments
– Product - arity and getting nth item in a
“cartesian product”.
• Subtraits are defined for Product,
called ProductN, for dimension N from 1 through
22.
– TupleN case classes for arity N = 1
through 22.
• Tuples support the literal syntax (x1, x2, …, xN)
43 of 99 Created on 10/01/2012
45. SIMPLE CLASS
–Like in Java classes are defined with class and
instances created with new
–Declaring properties is much simpler
Java Scala
public class Person { class Person (var name: String)
private String name = null;
public Person(String name) {
this.name = name;
} …
public String getName() { person = new Person(“Martin”)
return name; println(person.name)
}
public void setName(String name) {
this.name = name;
}
}
45 of 99 Created on 10/01/2012
46. SIMPLE CLASS
scala> class Lang {
| val name: String = “Scala"
| def add(m: Int, n: Int): Int = m + n
| }
defined class Lang
scala> val lang = new Lang
lang: Lang = Lang@e74a51
scala> lang.add(1, 2)
res1: Int = 3
scala> lang.name
res2: String = “Scala"
46 of 99 Created on 10/01/2012
48. EXTENDING CLASSES
class ArrayElement(conts: Array[String]) extends Element {
def contents: Array[String] = conts
}
class LineElement(s: String) extends ArrayElement(Array(s)) {
override def width = s.length
override def height = 1
}
48 of 99 Created on 10/01/2012
49. SINGLETON & COMPANION OBJECTS
– Scala is more object-oriented than Java is that classes in Scala
cannot have static members. Instead, Scala has singleton
objects.
– A singleton object definition looks like a class definition, except
instead of the keyword class you use the keyword object.
– When a singleton object shares the same name with a class, it
is called that class’s companion object.
object Rational {
…
}
– A singleton object that does not share the same name with a
companion class is called a standalone object.
49 of 99 Created on 10/01/2012
50. COMPANION OBJECT AS A FACTORY
– Companion objects are excellent fit for implementing
Factory design patterns
– Naming the method apply allows invocation like Array(“a”,
“b”, “c”) instead of Array.apply(“a”, “b”, “c”)
50 of 99 Created on 10/01/2012
51. BUILDER PATTERN IN SCALA
– From Josh Bloch’s “Effective Java” 2nd ed.:
public class NutritionFacts {
private final int servingSize; // (mL) required
private final int servings; // (per container) required
private final int calories; // optional
private final int fat; // (g) optional
private final int sodium; // (mg) optional
private final int carbohydrate;// (g) optional
… }
– In Scala:
class NutritionFacts(servingSize, servings, calories = 0, fat =
0, sodium = 0, carbohydrate = 0)
Creating an instance:
new NutritionFacts(servings = 3, servingSize = 200, fat = 1)
51 of 99 Created on 10/01/2012
52. CASE CLASSES – VALUE OBJECTS
case class Point(x: Double, y: Double)
abstract class Shape() { def draw(): Unit }
case class Circle(center: Point, radius: Double) extends Shape() {
def draw() { … }
}
case class Rectangle(x: Point, height: Double, width: Double) extends Shape() {
def draw() { … }
}
case class Triangle(point1: Point, point2: Point, point3: Point) extends Shape() {
def draw() { … }
}
– Using the case modifier makes the Scala compiler
add some syntactic conveniences to your class
•…
52 of 99 Created on 10/01/2012
53. CASE CLASS MAGIC
– Compiler automatically creates factory method:
val c = Circle(Point(2.0,1.0),3.0) instead of
val c = new Circle(new Point(2.0,1.0),3.0)
– All constructor arguments automatically become immutable fields
– Compiler automatically implements equals, hashCode, and toString
methods to the class, using the fields specified as constructor
arguments
case classes are always compared structurally
– Compiler adds a copy method for making modified copies
The method works by using named and default parameters. You specify the
changes you’d like to make by using named parameters. For any parameter
you don’t specify, the value from the old object is used.
val r = Rectangle(Point(1.0,2.0), 3.0, 4.0)
r.copy(height=5.0)
– We can pattern match on case classes…
53 of 99 Created on 10/01/2012
54. CASE CLASSES – PATTERN MATCHING
def matchOn(shape: Shape) = shape match {
case Circle(center, radius) =>
println("Circle: center = "+center+", radius = "+radius)
case Rectangle(x, h, w) =>
println("Rectangle: lower-left = "+x+", height = "+h+", width = "+w)
case Triangle(p1, p2, p3) =>
println("Triangle: point1 = "+p1+", point2 = "+p2+", point3 = "+p3)
case _ => println("Unknown shape!"+shape)
}
val shapesList = List(
Circle(Point(0.0, 0.0), 1.0), Circle(Point(5.0, 2.0), 3.0),
Rectangle(Point(0.0, 0.0), 2, 5), Rectangle(Point(-2.0, -1.0), 4, 3),
Triangle(Point(0.0, 0.0), Point(1.0, 0.0), Point(0.0, 1.0))
)
shapesList.foreach { shape => matchOn(shape) }
54 of 99 Created on 10/01/2012
56. TRAITS
– A trait definition looks just like a class definition except that it uses the
keyword trait
trait Philosophical {
def philosophize() { println("I consume memory, therefore I am!") }
}
– Once a trait is defined, it can be mixed in to a class using either the
extends or with keywords
class Frog extends Philosophical { … }
– Traits facilitate multiple inheritance: a class can mix in any number of
traits. “He who defs last defs best”.
class Animal { … }
trait HasLegs { val legsNumber : Int }
class Frog extends Animal with Philosophical with HasLegs {
override val legsNumber = 4
override def philosophize() { println(“It ain't easy being green”) }
}
56 of 99 Created on 10/01/2012
57. THE TRAITS OF TRAITS
– Traits can be also mixed in when creating individual
objects:
val frog = new Animal with Philosophical
– You can do anything in a trait definition that you can do in
a class definition, with only two exceptions:
• traitcannot have any “class” parameters, i.e., parameters passed to
the primary constructor of a class
trait NoPoint(x: Int, y: Int) // Does not compile
• in classes, super calls are statically bound, in traits, they are
dynamically bound (enables stackable modifications pattern)
– Trait, like any class can have a companion object
• selfless trait – trait Util { … }; object Util extends Util
57 of 99 Created on 10/01/2012
58. TRAITS – A PRACTICAL EXAMPLE
class Trade(refNo: String, account: String, instrument: String,
quantity: Int, unitPrice: Int) {
// principal value of the trade
def principal = quantity * unitPrice
}
trait Tax {
def calculateTax
}
trait Commission {
def calculateCommission
}
val trade = new Trade(..) with Tax with Commission {
// implementations
def calculateTax = principal * 0.2
def calculateCommission = principal * 0.15
}
58 of 99 Created on 10/01/2012
59. TRAITS – REQUIRE (SELF TYPE)
– Sometimes you want to constrain what the trait can be
mixed in with, for example:
// abstractions Tax and Commission should be constrained to be used
with the Trade abstraction only
trait Tax { self: Trade =>
def calculateTax = principal*0.2 //refers to principal of trade
}
trait Commission { self: Trade =>
def calculateCommission = principal*0.15 //refers to principal of trade
}
– When you say B extends A, then B is an A, while here you
define the relationship of B requires an A
59 of 99 Created on 10/01/2012
60. TRAITS – DI WITH THE CAKE PATTERN
– The pattern based on Scala traits was first introduced by Martin Odersky’s
paper “Scalable Component Abstractions”
– The pattern also uses nested classes: Scala, like Java, supports nesting of
classes in one another
– Demo
http://jonasboner.com/2008/10/06/real-world-scala-dependency-injection-di.html
60 of 99 Created on 10/01/2012
61. ANNOTATIONS – JPA EXAMPLE
@Entity
@NamedQuery{val name = "findAllBook", val query = "SELECT b FROM Book b"}
class Book extends Id with Description {
@Column{val nullable = false}
@BeanProperty var title: String
@BeanProperty var price: Float
@BeanProperty var isbn: String
@BeanProperty var nbOfPage: Int
@BeanProperty var illustrations: Boolean
}
trait Id {
@javax.persistence.Id
@GeneratedValue{val strategy = GenerationType.IDENTITY}
@BeanProperty var id: Long
}
trait Description {
@Column{val length = 2000}
@BeanProperty var description: String
}
61 of 99 Created on 10/01/2012
62. PACKAGES
– You can place code into named packages in Scala:
• Either place the contents of an entire file into a package by putting a package
clause at the top of the file (like in Java)
• Or follow a package clause by a section in curly braces that contains the
definitions that go into the package (like C# namespaces).
– Objects are a useful tool for organizing static functions.
62 of 99 Created on 10/01/2012
63. PACKAGE OBJECTS
– Scala version 2.8 introduces a new scoping construct
called package objects
• they are used to define types, variables, and methods that are visible
at the level of the corresponding package
• they can contain aliases to classes and objects
• they provide a clear separation between the abstractions exposed by
a package and the implementations that should be hidden inside it
package object scala {
type Iterable[+A] = scala.collection.Iterable[A]
val Iterable = scala.collection.Iterable
…
}
63 of 99 Created on 10/01/2012
64. IMPORT
– Use import in REPL and anywhere in your .scala file
• Single file: import package.Class
• All files: import package._
• Multiple files: import package.{A,B,C}
• Renaming: import package.{A=>B}
• Import all except: import package.{A=>_, _}
– Example:
import java.sql.{Date=>SDate,_}
– Imports are relative, but you can use _root_. … to import a FQN
– Import also works with Objects
– You can limit the scope of any declaration, including import, with
locally { … }
64 of 99 Created on 10/01/2012
66. OVERVIEW
– In mathematics, functions have no side effects
• No matter how much work sin(x) does, all the results are returned
and assigned to y. No global state of any kind is modified internally by
sin(x). Hence, we say that such a function is free of side-
effects or pure.
– This obliviousness to the surrounding context is known
as referential transparency.
• You can call such a function anywhere and be confident that it will
always behave the same way. If no global state is modified,
concurrent invocation of the function is straightforward and reliable.
66 of 99 Created on 10/01/2012
67. OVERVIEW
– In functional programming variables are immutable.
• In the expression y = sin(x), once you pick x, then y is fixed
• Functional programming languages prevent you from assigning a new value
to a variable that already has a value.
• Besides concurrency, immutability has other benefits…
– “Functional manifesto”
• valover var
• Composition over inheritance
• Immutable collections
• Recursion over imperative iteration
• Pattern matching over encapsulation
•…
67 of 99 Created on 10/01/2012
68. LAZY VAL
– If you prefix a val definition with a lazy modifier, the initializing
expression on the right-hand side will only be evaluated the first
time the val is used.
– unlike def, lazy val is never evaluated more than once.
• after the first evaluation of a lazy val the result of the evaluation is stored,
to be reused when the same val is used subsequently.
68 of 99 Created on 10/01/2012
69. CALL BY NAME PARAMETERS
–Typically, parameters to functions are by-
value parameters – the value of the parameter is
determined before it is passed to the function
–Sometimes we don’t want a parameter evaluated
until it’s accessed within our function
–A by-name parameter is specified by omitting the
parentheses that normally accompany a function
parameter
def myCall (parameter: => ReturnType)
69 of 99 Created on 10/01/2012
70. CALL BY NAME PARAMETERS USE-
CASE
– When logging, we create messages by concatenating Strings, even if we
don't use these messages in the end because the logging level is not
enabled.
– To fix the problem, we often insert manual checks in client code whether
the logging level is enabled, e.g. by calling
if (logger.isDebugEnabled()) logger.debug(…)
– SLF4S, Scala logging library, uses by-name parameters
def debug(msg: => String) {
require(msg != null, "msg must not be null!")
if (slf4jLogger.isDebugEnabled) slf4jLogger debug msg
}
– SLF4S also provides Logging trait that can be mixed in into any class
class MyClazz extends SomeClazz with Logging
...
logger debug "SLF4S just rocks!"
...
70 of 99 Created on 10/01/2012
71. CURRYING
– Currying – a way to write functions with multiple
parameter lists.
• For instance def f(x: Int)(y: Int) is a curried function with two
parameter lists.
• A curried function is applied by passing several arguments lists, as in:
f(3)(4).
– Examples:
def plainOldSum(x: Int, y: Int) = x + y
plainOldSum(1, 2)
def curriedSum(x: Int)(y: Int) = x + y
curriedSum(1)(2)
val onePlus: (Int) => Int = curriedSum(1)_
onePlus(2) //3
71 of 99 Created on 10/01/2012
72. CURRYING EXAMPLE
– foldLeft/Right
– withResource (the loan pattern)
def using[R <: Closeable] (resource: R)(block: R => Unit) {
try {
block(resource)
} finally {
if (resource != null) resource.close()
}
}
• Usage Example:
using(new BufferedReader(new FileReader("file"))) { r =>
… r.readLine …
}
72 of 99 Created on 10/01/2012
73. PARTIALLY-APPLIED FUNCTIONS
– A partially applied function is an expression in which you
don’t supply all of the arguments needed by the function.
Instead, you supply some, or none, of the needed
arguments.
scala> def sum(a: Int, b: Int, c: Int) = a + b + c
sum: (a: Int,b: Int,c: Int)Int
scala> val a = sum _
a: (Int, Int, Int) => Int = <function3>
a(1, 2, 3) //6
supplying some arguments: val b = sum(1, _: Int, 3)
b: (Int) => Int = <function1>
scala> b(2) //6
73 of 99 Created on 10/01/2012
75. MOTIVATION
Moor’s Law
• “The number of
transistors on a chip will
double approximately
every 18 months”
Gordon E. Moore, 1965
Free Lunch
Free and regular performance gains, even without releasing new
versions or doing anything special
75 of 99 Created on 10/01/2012
76. FREE LUNCH IS OVER
– Hardware crossed a boundary in the early 2000s:
• chips got big enough, cycle speed got fast enough
• a signal can no longer reach the whole chip in a clock cycle
• problems with heat dissipation
– Processor manufacturers have turned towards multi-core
processors Capable of doing multiple calculations in
parallel
• CPU speeds are likely to stay relatively flat in the near future
• The speedup of a program using multiple processors in parallel
computing is limited by the sequential fraction of the program.
76 of 99 Created on 10/01/2012
77. SHARED STATE CONCURRENCY
–Shared mutable state is problematic
–We need locking mechanism
–Thread concurrently executes code sections
• Contains resources that must be shared
• Synchronized in order to guarantee
−Correct ordering
−Visibility
−Data consistency
77 of 99 Created on 10/01/2012
78. PROBLEMS WITH LOCKING
–Hard to program correctly
• Race conditions
• Also hard to test and debug
–Synchronizing too much
• Deadlocks
• Makes your program serial
78 of 99 Created on 10/01/2012
80. ACTORS
–Message-passing instead of shared state
–Originated:
• CarlHewitt (early 70s)
• Gul Agha (80s)
–Popularized by Erlang implementation
• A pure functional, dynamically typed language invented in
1986 at Ericsson
–Actors are related to original OO ideas
• Actors encapsulate state and behavior (like objects)
• Actors are logically active (unlike most objects)
80 of 99 Created on 10/01/2012
81. ACTORS
– No shared state between actors
– Asynchronous message-passing
– Mailbox to buffer incoming
messages
– React to received messages by
executing a behavior function
• can only change the state of the actor itself
• can send messages to other actors
– Actors never share state and thus
never need to compete for locks for
access to shared data
81 of 99 Created on 10/01/2012
82. AKKA
– Akka is the platform for next generation event-driven, scalable, and
fault-tolerant architectures on the JVM
– Written in Scala, can be used with Scala or Java
– Each actor instance runs in only one thread at a time, so no
synchronization is required for actor state.
– Akka dispatcher schedules actors on threads – or even on multiple
machines – as needed. Can have millions of actors, an actor does not
“use up” a thread.
82 of 99 Created on 10/01/2012
83. SIMPLE AKKA ACTOR
case object Tick
class Counter extends Actor {
private var counter = 0
def receive = {
case Tick =>
counter += 1
println(counter)
}
}
val counter = actorOf[Counter]
counter.start
83 of 99 Created on 10/01/2012
84. SEND
–Fire and forget
counter ! Tick
–Uses Future under the hood (with time-out)
val result = (actor !! Message).as[String]
–Returns the Future directly
val future = actor !!! Message
future.await
val result = future.get
...
Futures.awaitOne(List(fut1, fut2, ...))
Futures.awaitAll(List(fut1, fut2, ...))
84 of 99 Created on 10/01/2012
85. REPLY
class SomeActor extends Actor {
def receive = {
case User(name) =>
// use reply
self.reply(“Hi ” + name)
}
}
store away the sender to use later or somewhere else
... = self.sender
85 of 99 Created on 10/01/2012
86. SCALA AND AKKA
– Immutable messages : case classes, tuples, lists
– Dispatchers
– Let it fail – Supervisor Hierarchies
• One for One
• All for One
• Supervise the supervisor
– Remote actors
– Transactors: STM using Actors
86 of 99 Created on 10/01/2012
88. SBT – SIMPLE BUILD TOOL
– Build your projects using Scala
– Create an sbt shell script: java -Xmx512M -jar sbt-launch.jar "$@“
– Launch it: sbt
– Interactive mode: e.g. compile
– Make an action run when a source file changes prefixing the action with ~.
– project/build/SbtDemoProject.scala
import sbt._
class SbtDemoProject(info: ProjectInfo) extends DefaultProject(info) {
val specs = "org.scala-tools.testing" % "specs_2.8.0" % "1.6.5" % "test"
lazy val hi = task { println("Hello World"); None }
override def compileOptions = super.compileOptions ++ Seq(Unchecked)
}
<dependency>
<groupId>org.scala-tools.testing</groupId>
– In sbt console: reload <artifactId>specs_2.8.0</artifactId>
<version>1.6.5</version>
<scope>test</scope>
– In sbt console: hi </dependency>
88 of 99 Created on 10/01/2012
89. PLAY! FRAMEWORK
– Both Scala and Java friendly
– Stateless
• Play is “share-nothing” so no need for communication between nodes
• State can be kept in your SQL or NoSQL store, in memcached, or browser cookies
– Emphasis on rapid development and good defaults, rather than
absolute flexibility
• No compile and restart; server compiles and recompiles on the fly, so just edit, reload,
edit, reload. Compilation and other errors appear right in the browser.
– Try out the Java or Scala tutorials on the Play website
play new helloworld --with scala
play run
89 of 99 Created on 10/01/2012
90. UNIT TESTING
–To test in Scala you can use Java tools:
• JUnit
• TestNG
–Or frameworks built especially for Scala:
• ScalaTest
• Specs
• ScalaCheck
90 of 99 Created on 10/01/2012
Scala
92. UNIT TESTING – SCALATEST + JUNIT
– If you wish to use ScalaTest’s assertion syntax in your JUnit 3 test, however, you
can instead subclass JUnit3Suite
– ScalaTest also has a JUnitWrapperSuite, which enables you to run existing JUnit
tests written in Java with ScalaTest’s runner.
92 of 99 Created on 10/01/2012
94. TEST AS SPECIFICATION
– In a FlatSpec, you write tests as specifier clauses.
• You start by writing a name for the subject under test as a string,
• then should (or must or can),
• then a string that specifies a bit of behavior required of the subject,
• then in.
• In the curly braces following in, you write code that tests the specified behavior.
• In subsequent clauses you can write it to refer to the most recently given subject.
– When a FlatSpec is executed, it will run each specifier clause as a ScalaTest
test.
• FlatSpec (and ScalaTest’s other specification traits) generate output that reads more like a
specification when run.
94 of 99 Created on 10/01/2012
Scala
95. TEST AS SPECIFICATION - SPECS
– specs is another open source testing framework inspired
by Ruby’s RSpec
95 of 99 Created on 10/01/2012
96. PROPERTY-BASED TESTING
– ScalaCheck enables you to specify properties that the code under test
must obey.
– For each property, ScalaCheck will generate test data and run tests
that check whether the property holds.
96 of 99 Created on 10/01/2012
98. MORE ON SCALA
– http://www.scala-lang.org
– http://typesafe.com/
– Scala School http://twitter.github.com/scala_school/
– Programming In Scala http://www.artima.com/pins1ed/
– Programming Scala http://ofps.oreilly.com/titles/9780596155957/
– Scala Style Guide http://davetron5000.github.com/scala-style/
– StackOverflow http://stackoverflow.com/questions/tagged/scala
98 of 99 Created on 10/01/2012
99. THANK YOU
If you are interested in programming languages,
join http://www.lambda.org.il
99 of 99 Created on 10/01/2012
Notas del editor
The major deviation from Java concerns the syntax for type annotations—it’s“variable: Type” instead of “Type variable” in Java. Scala’s postfix type syntax resemblesPascal, Modula-2, or Eiffel. The main reason for this deviation has to do with typeinference, which often lets you omit the type of a variable or the return type of a method.Using the “variable: Type” syntax this is easy—just leave out the colon and the type. Butin C-style “Type variable” syntax you cannot simply leave off the type—there would be nomarker to start the definition anymore. You’d need some alternative keyword to be a placeholderfor a missing type (C# 3.0, which does some type inference, uses var for this purpose).Such an alternative keyword feels more ad-hoc and less regular than Scala’s approach.
That plus sign between the strings? It’s a method. First, Scala allows non-alphanumeric method names. You can call methods +, -, $, or whatever you desire. Second, this expression is identical to 1 .+(2). (We put a space after the 1 because 1. would be interpreted as aDouble.) When a method takes one argument, Scala lets you drop both the period and the parentheses, so the method invocation looks like an operator invocation. This is called “infix” notation, where the operator is between the instance and the argument. We’ll find out more about this shortly.To facilitate a variety of readable programming styles, Scala is flexible about the use of parentheses in methods. If a method takes no parameters, you can define it without parentheses. Callers must invoke the method without parentheses. If you add empty parentheses, then callers may optionally add parentheses. For example, the size method for List has no parentheses, so you write List(1, 2, 3).size. If you try List(1, 2, 3).size(), you’ll get an error. However, the length method for String does have parentheses in its definition, so both"hello".length() and "hello".length will compile.The convention in the Scala community is to omit parentheses when calling a method that has no side-effects. So, asking for the size of a sequence is fine without parentheses, but defining a method that transforms the elements in the sequence should be written with parentheses.It’s also possible to omit the dot (period) when calling a parameterless method or one that takes only one argument
Because map takes one argument, a function, we can use the “placeholder” indicator _ instead of a named parameter. That is, the _ acts like an anonymous variable, to which each string will be assigned before toUpperCase is called. Note that the String type is inferred for us, too. As we will see, Scala uses _ as a “wild card” in several contexts.