19. public abstract class Animal { abstract class Animal {
public abstract String getName(); def name: String
@Override public String toString() override def toString(): String = {
{
// . . . Calc. class name
// . . . Calc. class name
shortClassName + " " + name
return shortClassName +
" " + getName();
}
}
}
}
Bla bla class
Animal bla bla
bla . . . Class
Animal.
20. public class Cat extends Animal { class Cat (
val name: String
private final String name;
) extends Animal
public Cat(String name) {
this.name = name;
}
@Override public String getName() {
return name;
}
}
Bla a Cat is an Animal
with a fixed name, when
I make one I have to
give it a name and bla A cat is an
bla I can ask for the animal with a
name and will answer fixed name.
with the given name.
21. Uniform Access Principle
abstract class Animal {
Subclas
ses can
def name: String // method
access refine
a
represe nd
}
ntation
class Cat ( !
val name: String // immutable
) extends Animal
class Dog ( class Dog (name: String) extends
Animal {
var name: String // mutable private var _name: String = name
) extends Animal
def name : String = _name
def name_= (name: String) {
_name = name
}
}
22. public interface Iterable<T> { trait Iterable[+A] {
Iterator<T> iterator(); def elements: Iterator[A]
def map[B](f: A => B): Iterable[B] =
}
...
def flatMap[B](f: A => Iterable[B]):
Iterable[B] =
...
aits
def filter(p: A => Boolean):
Iterable[A] =
Tr
...
def partition(p: A => Boolean):
(Iterable[A], Iterable[A]) = {
...
}
...
} Traits: abstract and
Interfaces: only concrete methods
abstract methods
Rich interfaces!
Sparse
interfaces!
23. More on Types
Gener
ics tha
t jus t
work!
(vs 513
pages
of F.A.Q
.)
Variance Declaratio
ns
s
Abstract Type
28. import java.io.File; import java.io.File
import RichFile.apply
File cwd = new File("."); val cwd = new File(".")
for (File f: for (f <- cwd / "src" ) {
new File(cwd,"src").listFiles()) { println(file)
value / is not a member of
System.out.println(f); }
java.io.File
}
object RichFile {
implicit def apply(f: File):
RichFile
= new RichFile(f)
}
29. import java.io.File
package files
import RichFile.apply
import java.io.File val cwd = new File(".")
class RichFile( for (f <- cwd / "src" ) {
private val underlying: File
) extends Iterable[File] { println(file)
}
def elements: Iterator[File] = {
val files = underlying.listFiles()
if (files == null)
Iterator.empty
else
files.elements
}
def /(child: String): File =
new File(underlying, child)
}
object RichFile {
implicit def apply(file: File): RichFile =
new RichFile(file)
}
31. Higher Order Functions
val listBuffer = new ListBuffer[File] val listBuffer = new ListBuffer[File]
for (file <- currentDir) { for (file <- currentDir) {
if (file.isDirectory) { if (file.getName.startsWith(p)) {
listBuffer += file listBuffer += file
} }
} }
println(listBuffer) println(listBuffer)
val listBuffer = new ListBuffer[File] val listBuffer = new ListBuffer[File]
for (file <- currentDir) { for (file <- currentDir) {
if (file.canRead) { if (predicate(file)) {
listBuffer += file listBuffer += file
} }
} }
println(listBuffer) println(listBuffer)
32. Higher Order Functions
package java.io;
public interface FileFilter {
boolean accept(File pathname);
Templa
}
te Patt
here.listFiles(new FileFilter() {
ern
@Override
public boolean accept(File f) {
return f.isDirectory();
}
});
Act ionListener
mplate
Hiberna
teTemp Transa ctionTe
late
33. Higher Order Functions
package java.io;
public interface FileFilter {
boolean accept(File pathname);
Templa
}
te Patt
here.listFiles(new FileFilter() {
ern
@Override
public boolean accept(File f) {
return f.isDirectory();
}
});
Act ionListener
mplate
Hiberna
teTemp Transa ctionTe
late
34. Higher Order Functions
// in class RichFile
def collect(predicate: File=>Boolean): List[File] = {
val listBuffer = new ListBuffer[File]
for (file <- this)
if (predicate(file))
function
listBuffer += file
type
listBuffer.toList
}
def fileIsDirectory(file: File): Boolean = file.isDirectory
println(currentDir.collect(fileIsDirectory))
function value
println(currentDir.collect((f: File) => f.isDirectory))
function literal
println(currentDir.collect(f => f.isDirectory))
println(currentDir.collect(_.isDirectory))
35. Altern atively
// in class RichFile
def listFiles (predicate: File=>Boolean): Array[File] =
underlying.listFiles(new FileFilter {
def accept(f: File) = predicate(f)
})
val currentDir = new File(".")
println(currentDir.listFiles((f: File) => f.isDirectory))
But…
36. Higher Order Functions
// in class RichFile
def collect(predicate: File=>Boolean): List[File] = {
val listBuffer = new ListBuffer[File]
for (file <- this)
if (predicate(file))
listBuffer += file
listBuffer.toList
}
def fileIsDirectory(file: File): Boolean = file.isDirectory
println(currentDir.collect(fileIsDirectory))
println(currentDir.collect((f: File) => f.isDirectory))
println(currentDir.collect(f => f.isDirectory))
println(currentDir.collect(_.isDirectory))
37. Higher Order Functions
// in class RichFile
def collect(predicate: File=>Boolean): List[File] = {
val listBuffer = new ListBuffer[File]
“collect” is
for (file <- this)
if Iterable.filter
(predicate(file))
listBuffer += file
listBuffer.toList
}
def fileIsDirectory(file: File): Boolean = file.isDirectory
println(currentDir.filter(fileIsDirectory))
println(currentDir.filter((f: File) => f.isDirectory))
println(currentDir.filter(f => f.isDirectory))
println(currentDir.filter(_.isDirectory))
40. Function Literals and Closures
// variable i is bound
(i: Int) => i * 2
// variable i is bound, factor is unbound
// “open” expression
(i: Int) => factor * i
// “open” expression is closed by binding factor
val factor = 2
val closure = (i: Int) => factor * i
// closure object remembers the factor
assert( closure(3) == 6 )
41. Closures aren’t new!
Lisp
Scheme Smalltalk
Python Ruby
Perl
PHP Haskell OCaml
JavaScript C#
Groovy
Functional
Source: Seite „Closure“. In: Wikipedia, Die freie Enzyklopädie. Bearbeitungsstand: 7. Juni 2009,
Other paradigm
09:48 UTC. URL: http://de.wikipedia.org/w/index.php?title=Closure&oldid=60866571 (Abgerufen:
11. Juni 2009, 22:49 UTC)
44. int x = 7; val x = 7;
switch (x) { x match {
case 1: case 1 =>
System.out.println("one"); println("one")
break;
case 2: case 2 =>
System.out.println("two"); println("two")
break;
default: case _ =>
System.out.println("many"); println("many")
break; }
}
45. int x = 7; val x = 7;
switch (x) { x match {
case 1: case 1 =>
System.out.println("one"); println("one")
break;
case 2: case 2 =>
System.out.println("two"); println("two")
break;
default: case _ =>
System.out.println("many"); println("many")
break; }
}
val x = 7;
val text = x match {
case 1 => "one"
case 2 => "two"
case _ => "many"
}
println(text)
46. var force = false
var help = false
val opt = "-help";
opt match {
case "-force" => force = true
case "-help" => help = true
case _ => throw new …
}
47. sealed abstract class Shape
case class Circle(radius: Double) extends Shape
case class Rectangle(x: Double, y: Double) extends
Shape
def area(shape: Shape): Double = shape match {
case Circle(r) => r * r * PI
case Rectangle(x,y) => x * y
}
println(area(Circle(3.0)))
49. Exception in thread "main"
java.lang.NullPointerException
def isEven(i: Int) = i % 2 == 0
val found = List(1, 2, 3).find(isEven)
// won’t compile
// val half = found / 2
found match { value / is not a
case None => member of Option[Int]
“I call it my billion- println("No even value")
dollar mistake. case Some(i) =>
println("First even falue: " + i)
}
It was the invention
of the null reference
in 1965. “
-- Tony Hoare
51. “As soon as you start sharing memory,
you are hosed” – Bruce Eckel
Photo: Adam Klepsteen
52. case object Fly
Messag
val tweetie = new Bird
e-Pass
tweetie.start() Concurr ing
ency:
tweetie ! Fly Erlang
Style
Actors
class Bird extends Actor {
def act {
loop {
receive {
case Fly => println("Flying")
case other => println("What? " + other)
}
}
}
}
53. Tools
• Compiler: scalac
• Interpreter (“REPL”): scala
• IDE: Eclipse, Netbeans, IDEA
• Build Systems: Ant, Maven, SBT
Eclipse plugin usable, but far from perfect!
54. Users
• (message routing middleware)
• (energy trading)
(Sponsor of Eclipse plugin)
• (community site)
• Sony Pictures (middleware)
55. Books
Programming in Scala – Available Now
by Martin Odersky, Lex Spoon, and Bill Venners
Beginning Scala – Available Now
by David Pollak.
Published by Apress and also available from Amazon.
The Definitive Guide to Lift – Available Now
Scala-based Web Framework
By Derek Chen-Becker, Tyler Weir, Marius Danciu
Programming Scala – Available August, 2009
("Rough cuts" available now)
By Alex Payne and Dean Wampler