Your SlideShare is downloading. ×
Fast Forward to Scala




    A quick introduction to Scala
       for Java programmers



 Martin Kneißl http://kneissl.e...
Computers get faster all the time
Computers get faster all the time
                                                      The Future
 10000                 ...
Computers get faster all the time

                          73728
                            *
                         ...
Photo by Kamil Dratwa
Photo by John Trif, Melbourne
Photo: Jay Simmons




 ow y
H n
  a s
 m re
  co s a ial
    oe ent ur
   d u
      q f yo se?
   se t o    u
      ar ra...
“As soon as you start sharing memory,
   you are hosed” – Bruce Eckel




                                 Photo: Adam Kle...
Don’t share!
        Use messaging instead.




 Don’t modify!
         Create new values instead.
Object                          Functional
    Oriented                                   Tr
                             ...
Object                           Functional
 Oriented                               Tr
                                   ...
Photo: adriaan de man




I like static types
Photo: adriaan de man
Photo: adriaan de man



           e  to wait
D on’t hav e to
un t il runtim
            !
 f ind this
Avoid RSI




            Photo: Ginny Austin
Use Scala!




             Photo: Ginny Austin
public abstract class Animal {           abstract class Animal {


    public abstract String getName();        def name: ...
public class Cat extends Animal {         class Cat (
                                           val name: String
    priv...
Uniform Access Principle
abstract class Animal {
                                              Subclas
                   ...
public interface Iterable<T> {   trait Iterable[+A] {

    Iterator<T> iterator();          def elements: Iterator[A]
    ...
More on Types

 Gener
      ics tha
                   t jus t
                             work!
    (vs 513
            ...
Photo: Carl Lender, New Haven, CT
import java.io.File;                     import java.io.File
                                         import RichFile.appl...
import java.io.File
package files
                                           import RichFile.apply
import java.io.File    ...
Functional Programming
•   Immutability
•   Higher Order Functions
•   Closures
•   Pattern matching
•   Recursion
Higher Order Functions
val listBuffer = new ListBuffer[File]   val listBuffer = new ListBuffer[File]
for (file <- currentD...
Higher Order Functions
package java.io;
public interface FileFilter {
      boolean accept(File pathname);
               ...
Higher Order Functions
package java.io;
public interface FileFilter {
      boolean accept(File pathname);
               ...
Higher Order Functions
// in class RichFile
def collect(predicate: File=>Boolean): List[File] = {
    val listBuffer = new...
Altern atively
// in class RichFile
def listFiles (predicate: File=>Boolean): Array[File] =
   underlying.listFiles(new Fi...
Higher Order Functions
// in class RichFile
def collect(predicate: File=>Boolean): List[File] = {
    val listBuffer = new...
Higher Order Functions
// in class RichFile
def collect(predicate: File=>Boolean): List[File] = {
    val listBuffer = new...
Higher Order Functions




println(currentDir.filter(_.isDirectory))




println(currentDir.filter(_.getName.startsWith(p)...
Higher Order Functions
val numbers = 1 to 3
assert( numbers                     sameElements List(1, 2, 3) )


assert( num...
Function Literals and Closures
// variable i is bound
(i: Int) => i * 2



// variable i is bound, factor is unbound
// “o...
Closures aren’t new!
        Lisp
                                  Scheme                                           Small...
Pattern Matching
int x = 7;                              val x = 7;
switch (x) {                            x match {
case 1:              ...
int x = 7;                              val x = 7;
switch (x) {                            x match {
case 1:              ...
var force = false
var help = false
val opt = "-help";
opt match {
    case "-force" => force = true
    case "-help"   => ...
sealed abstract class Shape


case class Circle(radius: Double) extends Shape


case class Rectangle(x: Double, y: Double)...
Exception in thread "main"
java.lang.NullPointerException
Exception in thread "main"
           java.lang.NullPointerException
                          def isEven(i: Int) = i % 2 ...
Some(null)




    Photo: Anna Humphreys, UK
“As soon as you start sharing memory,
   you are hosed” – Bruce Eckel




                                 Photo: Adam Kle...
case object Fly


                                                 Messag
val tweetie = new Bird
                         ...
Tools
•   Compiler: scalac
•   Interpreter (“REPL”): scala
•   IDE: Eclipse, Netbeans, IDEA
•   Build Systems: Ant, Maven,...
Users
•              (message routing middleware)

•                 (energy trading)
    (Sponsor of Eclipse plugin)

•  ...
Books
Programming in Scala – Available Now
by Martin Odersky, Lex Spoon, and Bill Venners


Beginning Scala – Available No...
Other Resources

• http://www.scala-lang.org/

• Mailinglisten, Blogs

• #scala on IRC

• #scala on twitter
Avoid RSI




            Photo: Ginny Austin
Use Scala!




             Photo: Ginny Austin
Fast Forward To Scala
Fast Forward To Scala
Fast Forward To Scala
Fast Forward To Scala
Fast Forward To Scala
Fast Forward To Scala
Upcoming SlideShare
Loading in...5
×

Fast Forward To Scala

3,433

Published on

A quick introduction to Scala
for Java programmers

- Audio to follow, soon.
- Animation and part of the layout has been killed by SlideShare :-(

Published in: Technology, News & Politics
0 Comments
10 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
3,433
On Slideshare
0
From Embeds
0
Number of Embeds
5
Actions
Shares
0
Downloads
0
Comments
0
Likes
10
Embeds 0
No embeds

No notes for slide

Transcript of "Fast Forward To Scala"

  1. 1. Fast Forward to Scala A quick introduction to Scala for Java programmers Martin Kneißl http://kneissl.eu/Members/martin/blog
  2. 2. Computers get faster all the time
  3. 3. Computers get faster all the time The Future 10000 100000 Clockspeed "Total Speed" Memory 10000 1000 1000 100 100 10 Martin’s PCs 10 Dark Ages 1 1 1985 1990 1995 2000 2005 2010 2015
  4. 4. Computers get faster all the time 73728 * 32-bit 850 MHz * 4 cores 1 000 000 000 000 000 FLOP/s
  5. 5. Photo by Kamil Dratwa
  6. 6. Photo by John Trif, Melbourne
  7. 7. Photo: Jay Simmons ow y H n a s m re co s a ial oe ent ur d u q f yo se? se t o u ar ram p g p ro
  8. 8. “As soon as you start sharing memory, you are hosed” – Bruce Eckel Photo: Adam Klepsteen
  9. 9. Don’t share! Use messaging instead. Don’t modify! Create new values instead.
  10. 10. Object Functional Oriented Tr ming ansfor alues ulated able v E ncaps tate i mmut le s mutab a add: x a := a + x a b a b x x
  11. 11. Object Functional Oriented Tr ming ansfor alues ulated able v E ncaps tate Immut le s mutab “Deep” Concise Statically Typed Compatible
  12. 12. Photo: adriaan de man I like static types
  13. 13. Photo: adriaan de man
  14. 14. Photo: adriaan de man e to wait D on’t hav e to un t il runtim ! f ind this
  15. 15. Avoid RSI Photo: Ginny Austin
  16. 16. Use Scala! Photo: Ginny Austin
  17. 17. 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.
  18. 18. 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.
  19. 19. 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 } }
  20. 20. 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!
  21. 21. More on Types Gener ics tha t jus t work! (vs 513 pages of F.A.Q .) Variance Declaratio ns s Abstract Type
  22. 22. Photo: Carl Lender, New Haven, CT
  23. 23. 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) }
  24. 24. 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) }
  25. 25. Functional Programming • Immutability • Higher Order Functions • Closures • Pattern matching • Recursion
  26. 26. 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)
  27. 27. 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
  28. 28. 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
  29. 29. 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))
  30. 30. 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…
  31. 31. 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))
  32. 32. 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))
  33. 33. Higher Order Functions println(currentDir.filter(_.isDirectory)) println(currentDir.filter(_.getName.startsWith(p)) println(currentDir.filter(_.canRead))
  34. 34. Higher Order Functions val numbers = 1 to 3 assert( numbers sameElements List(1, 2, 3) ) assert( numbers.map(_ * 2) sameElements List(2, 4, 6) ) assert( numbers.reduceLeft(_ + _) == 1 + 2 + 3 ) assert( numbers.foldLeft("")(_ + _) == "" + 1 + 2 + 3 ) assert( ("" /: numbers)(_ + _) == "" + 1 + 2 + 3 )
  35. 35. 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 )
  36. 36. 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)
  37. 37. Pattern Matching
  38. 38. 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; } }
  39. 39. 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)
  40. 40. var force = false var help = false val opt = "-help"; opt match { case "-force" => force = true case "-help" => help = true case _ => throw new … }
  41. 41. 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)))
  42. 42. Exception in thread "main" java.lang.NullPointerException
  43. 43. 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
  44. 44. Some(null) Photo: Anna Humphreys, UK
  45. 45. “As soon as you start sharing memory, you are hosed” – Bruce Eckel Photo: Adam Klepsteen
  46. 46. 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) } } } }
  47. 47. Tools • Compiler: scalac • Interpreter (“REPL”): scala • IDE: Eclipse, Netbeans, IDEA • Build Systems: Ant, Maven, SBT Eclipse plugin usable, but far from perfect!
  48. 48. Users • (message routing middleware) • (energy trading) (Sponsor of Eclipse plugin) • (community site) • Sony Pictures (middleware)
  49. 49. 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
  50. 50. Other Resources • http://www.scala-lang.org/ • Mailinglisten, Blogs • #scala on IRC • #scala on twitter
  51. 51. Avoid RSI Photo: Ginny Austin
  52. 52. Use Scala! Photo: Ginny Austin

×