SlideShare ist ein Scribd-Unternehmen logo
1 von 58
Fast Forward to Scala




    A quick introduction to Scala
       for Java programmers



 Martin Kneißl http://kneissl.eu/Members/martin/blog
Computers get faster all the time
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
Computers get faster all the time

                          73728
                            *
                          32-bit
                         850 MHz
                            *
                         4 cores

1 000 000 000 000 000 FLOP/s
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 ram
    p g
      p ro
“As soon as you start sharing memory,
   you are hosed” – Bruce Eckel




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




 Don’t modify!
         Create new values instead.
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
Object                           Functional
 Oriented                               Tr
                                                ming
                                          ansfor alues
                ulated                      able v
         E ncaps tate                 Immut
               le s
         mutab




                         “Deep”      Concise
Statically
 Typed
                              Compatible
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: 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.
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.
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
                                          }
                                      }
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!
More on Types

 Gener
      ics tha
                   t jus t
                             work!
    (vs 513
              pages
                    of F.A.Q
                            .)


                                     Variance Declaratio
                                                         ns


                            s
              Abstract Type
Photo: Carl Lender, New Haven, CT
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)
                                         }
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)
}
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 <- 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)
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
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
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))
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…
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))
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))
Higher Order Functions




println(currentDir.filter(_.isDirectory))




println(currentDir.filter(_.getName.startsWith(p))




println(currentDir.filter(_.canRead))
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   )
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 )
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)
Pattern Matching
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;                        }
}
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)
var force = false
var help = false
val opt = "-help";
opt match {
    case "-force" => force = true
    case "-help"   => help   = true
    case _         => throw new …
}
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)))
Exception in thread "main"
java.lang.NullPointerException
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
Some(null)




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




                                 Photo: Adam Klepsteen
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)
            }
        }
    }
}
Tools
•   Compiler: scalac
•   Interpreter (“REPL”): scala
•   IDE: Eclipse, Netbeans, IDEA
•   Build Systems: Ant, Maven, SBT

Eclipse plugin usable, but far from perfect!
Users
•              (message routing middleware)

•                 (energy trading)
    (Sponsor of Eclipse plugin)

•         (community site)

• Sony Pictures (middleware)
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
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

Weitere ähnliche Inhalte

Was ist angesagt?

Chapter 04 inheritance
Chapter 04 inheritanceChapter 04 inheritance
Chapter 04 inheritanceNurhanna Aziz
 
Intro to threp
Intro to threpIntro to threp
Intro to threpHong Wu
 
The Ruby Object Model by Rafael Magana
The Ruby Object Model by Rafael MaganaThe Ruby Object Model by Rafael Magana
The Ruby Object Model by Rafael MaganaRafael Magana
 
Intro to Python (High School) Unit #2
Intro to Python (High School) Unit #2Intro to Python (High School) Unit #2
Intro to Python (High School) Unit #2Jay Coskey
 
Java class 4
Java class 4Java class 4
Java class 4Edureka!
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheoryKnoldus Inc.
 
String handling session 5
String handling session 5String handling session 5
String handling session 5Raja Sekhar
 
Introduction To Javascript
Introduction To JavascriptIntroduction To Javascript
Introduction To JavascriptRajat Pandit
 
Scala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosScala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosGenevaJUG
 
Peyton jones-2011-type classes
Peyton jones-2011-type classesPeyton jones-2011-type classes
Peyton jones-2011-type classesTakayuki Muranushi
 

Was ist angesagt? (19)

Lecture Notes
Lecture NotesLecture Notes
Lecture Notes
 
Chapter 04 inheritance
Chapter 04 inheritanceChapter 04 inheritance
Chapter 04 inheritance
 
Groovy intro for OUDL
Groovy intro for OUDLGroovy intro for OUDL
Groovy intro for OUDL
 
Intro to threp
Intro to threpIntro to threp
Intro to threp
 
ruby1_6up
ruby1_6upruby1_6up
ruby1_6up
 
The Ruby Object Model by Rafael Magana
The Ruby Object Model by Rafael MaganaThe Ruby Object Model by Rafael Magana
The Ruby Object Model by Rafael Magana
 
Intro to Python (High School) Unit #2
Intro to Python (High School) Unit #2Intro to Python (High School) Unit #2
Intro to Python (High School) Unit #2
 
Java class 4
Java class 4Java class 4
Java class 4
 
JavaYDL17
JavaYDL17JavaYDL17
JavaYDL17
 
Cb25464467
Cb25464467Cb25464467
Cb25464467
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
 
String handling session 5
String handling session 5String handling session 5
String handling session 5
 
Introduction To Javascript
Introduction To JavascriptIntroduction To Javascript
Introduction To Javascript
 
Lecture 03
Lecture 03Lecture 03
Lecture 03
 
Ch2 Liang
Ch2 LiangCh2 Liang
Ch2 Liang
 
Scala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosScala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian Dragos
 
Peyton jones-2011-type classes
Peyton jones-2011-type classesPeyton jones-2011-type classes
Peyton jones-2011-type classes
 

Andere mochten auch

Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to ScalaSynesso
 
An Introduction to Scala (2014)
An Introduction to Scala (2014)An Introduction to Scala (2014)
An Introduction to Scala (2014)William Narmontas
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from javaIndicThreads
 
Scala Development Tools
Scala Development ToolsScala Development Tools
Scala Development ToolsHiraq Citra M
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scalaXing
 
An Introduction to Scala
An Introduction to ScalaAn Introduction to Scala
An Introduction to ScalaBrent Lemons
 
Introduction to Asynchronous scala
Introduction to Asynchronous scalaIntroduction to Asynchronous scala
Introduction to Asynchronous scalaStratio
 
A (too) Short Introduction to Scala
A (too) Short Introduction to ScalaA (too) Short Introduction to Scala
A (too) Short Introduction to ScalaRiccardo Cardin
 
Introduction to scala
Introduction to scalaIntroduction to scala
Introduction to scalaMichel Perez
 

Andere mochten auch (12)

Scala introduction
Scala introductionScala introduction
Scala introduction
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
An Introduction to Scala (2014)
An Introduction to Scala (2014)An Introduction to Scala (2014)
An Introduction to Scala (2014)
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
 
Scala Development Tools
Scala Development ToolsScala Development Tools
Scala Development Tools
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
An Introduction to Scala
An Introduction to ScalaAn Introduction to Scala
An Introduction to Scala
 
Introduction to Asynchronous scala
Introduction to Asynchronous scalaIntroduction to Asynchronous scala
Introduction to Asynchronous scala
 
A (too) Short Introduction to Scala
A (too) Short Introduction to ScalaA (too) Short Introduction to Scala
A (too) Short Introduction to Scala
 
Introduction to scala
Introduction to scalaIntroduction to scala
Introduction to scala
 
Scala vs Ruby
Scala vs RubyScala vs Ruby
Scala vs Ruby
 

Ähnlich wie Fast Forward To Scala

The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Languageleague
 
Inheritance And Traits
Inheritance And TraitsInheritance And Traits
Inheritance And TraitsPiyush Mishra
 
Mastering Kotlin Standard Library
Mastering Kotlin Standard LibraryMastering Kotlin Standard Library
Mastering Kotlin Standard LibraryNelson Glauber Leal
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic ProgrammingPingLun Liao
 
2.1 recap from-day_one
2.1 recap from-day_one2.1 recap from-day_one
2.1 recap from-day_onefuturespective
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to ScalaBrian Hsu
 
Intro to scala
Intro to scalaIntro to scala
Intro to scalaJoe Zulli
 
Lesson 18: Maximum and Minimum Vaues
Lesson 18: Maximum and Minimum VauesLesson 18: Maximum and Minimum Vaues
Lesson 18: Maximum and Minimum VauesMatthew Leingang
 
Lesson 18: Maximum and Minimum Vaues
Lesson 18: Maximum and Minimum VauesLesson 18: Maximum and Minimum Vaues
Lesson 18: Maximum and Minimum VauesMatthew Leingang
 
Lesson 19: Maximum and Minimum Values
Lesson 19: Maximum and Minimum ValuesLesson 19: Maximum and Minimum Values
Lesson 19: Maximum and Minimum ValuesMatthew Leingang
 
Lesson19 Maximum And Minimum Values 034 Slides
Lesson19   Maximum And Minimum Values 034 SlidesLesson19   Maximum And Minimum Values 034 Slides
Lesson19 Maximum And Minimum Values 034 SlidesMatthew Leingang
 
Kotlin Delegates: Reduce the boilerplate
Kotlin Delegates: Reduce the boilerplateKotlin Delegates: Reduce the boilerplate
Kotlin Delegates: Reduce the boilerplateDmytro Zaitsev
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
ES6 General Introduction
ES6 General IntroductionES6 General Introduction
ES6 General IntroductionThomas Johnston
 
Design patterns with Kotlin
Design patterns with KotlinDesign patterns with Kotlin
Design patterns with KotlinAlexey Soshin
 

Ähnlich wie Fast Forward To Scala (20)

The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Inheritance And Traits
Inheritance And TraitsInheritance And Traits
Inheritance And Traits
 
Mastering Kotlin Standard Library
Mastering Kotlin Standard LibraryMastering Kotlin Standard Library
Mastering Kotlin Standard Library
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic Programming
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
 
2.1 recap from-day_one
2.1 recap from-day_one2.1 recap from-day_one
2.1 recap from-day_one
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Intro to scala
Intro to scalaIntro to scala
Intro to scala
 
Lesson 18: Maximum and Minimum Vaues
Lesson 18: Maximum and Minimum VauesLesson 18: Maximum and Minimum Vaues
Lesson 18: Maximum and Minimum Vaues
 
Lesson 18: Maximum and Minimum Vaues
Lesson 18: Maximum and Minimum VauesLesson 18: Maximum and Minimum Vaues
Lesson 18: Maximum and Minimum Vaues
 
Lesson 19: Maximum and Minimum Values
Lesson 19: Maximum and Minimum ValuesLesson 19: Maximum and Minimum Values
Lesson 19: Maximum and Minimum Values
 
Lesson19 Maximum And Minimum Values 034 Slides
Lesson19   Maximum And Minimum Values 034 SlidesLesson19   Maximum And Minimum Values 034 Slides
Lesson19 Maximum And Minimum Values 034 Slides
 
Kotlin Delegates: Reduce the boilerplate
Kotlin Delegates: Reduce the boilerplateKotlin Delegates: Reduce the boilerplate
Kotlin Delegates: Reduce the boilerplate
 
Design pattern
Design patternDesign pattern
Design pattern
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
ES6 General Introduction
ES6 General IntroductionES6 General Introduction
ES6 General Introduction
 
Design patterns with Kotlin
Design patterns with KotlinDesign patterns with Kotlin
Design patterns with Kotlin
 

Kürzlich hochgeladen

Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 

Kürzlich hochgeladen (20)

Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 

Fast Forward To Scala

  • 1. Fast Forward to Scala A quick introduction to Scala for Java programmers Martin Kneißl http://kneissl.eu/Members/martin/blog
  • 2.
  • 3. Computers get faster all the time
  • 4. 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
  • 5. Computers get faster all the time 73728 * 32-bit 850 MHz * 4 cores 1 000 000 000 000 000 FLOP/s
  • 6. Photo by Kamil Dratwa
  • 7. Photo by John Trif, Melbourne
  • 8.
  • 9. 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
  • 10. “As soon as you start sharing memory, you are hosed” – Bruce Eckel Photo: Adam Klepsteen
  • 11. Don’t share! Use messaging instead. Don’t modify! Create new values instead.
  • 12. 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
  • 13. Object Functional Oriented Tr ming ansfor alues ulated able v E ncaps tate Immut le s mutab “Deep” Concise Statically Typed Compatible
  • 14. Photo: adriaan de man I like static types
  • 16. Photo: adriaan de man e to wait D on’t hav e to un t il runtim ! f ind this
  • 17. Avoid RSI Photo: Ginny Austin
  • 18. Use Scala! Photo: Ginny Austin
  • 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
  • 24.
  • 25.
  • 26. Photo: Carl Lender, New Haven, CT
  • 27.
  • 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) }
  • 30. Functional Programming • Immutability • Higher Order Functions • Closures • Pattern matching • Recursion
  • 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))
  • 39. 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 )
  • 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)
  • 42.
  • 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)))
  • 48. Exception in thread "main" java.lang.NullPointerException
  • 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
  • 50. Some(null) Photo: Anna Humphreys, UK
  • 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
  • 56. Other Resources • http://www.scala-lang.org/ • Mailinglisten, Blogs • #scala on IRC • #scala on twitter
  • 57. Avoid RSI Photo: Ginny Austin
  • 58. Use Scala! Photo: Ginny Austin