SlideShare ist ein Scribd-Unternehmen logo
1 von 28
Downloaden Sie, um offline zu lesen
Scala
@ TechMeetup Edinburgh

   Stuart Roebuck
   stuart.roebuck@proinnovate.com
What does ProInnovate do?




TOP SECRET
The basics…
• Scala stands for ‘scalable language’
• Scala runs on the Java Virtual Machine ( JVM)
• Created by Martin Odersky (EPFL)
           • he previously created the Pizza language
             with Philip Wadler (now at Edinburgh
             University)
           • …then GJ (Generic Java) that became
             Java Generics in the official Java 5.0
             release for which he apologises!
How long has it been
             around?


• Scala 1.0 appeared in 2003
• Scala 2.0 appeared in 2006
• Scala 2.7.7 is the current stable release


• Scala 2.8 beta 1 is due for release any day now!
“If I were to pick a language to
use today other than Java, it
would be Scala”
                   James Gosling
Try this at home!

• Scala home: http://www.scala-lang.org/
• Downloadable for Mac, Linux & Windows
• Shell interpreter: scala
• Compilers: scalac and fsc
• Documentation generator scaladoc
• Plugins for Eclipse, Netbeans, IntelliJ
Hello World!
->scala
Welcome to Scala version 2.7.7.final (Java HotSpot
(TM) 64-Bit Server VM, Java 1.6.0_17).
Type in expressions to have them evaluated.
Type :help for more information.

scala> def main { println("Hello World!") }
main: Unit

scala> main
Hello World!
Build tools +

• Maven Plugin (no endorsement implied)—http://
  scala-tools.org/mvnsites/maven-scala-plugin/
• simple-build-tool—http://code.google.com/p/
  simple-build-tool/
• Apache Ant tasks for Scala—http://www.scala-
  lang.org/node/98
• Apache Buildr—http://buildr.apache.org/
• JavaRebel—http://www.zeroturnaround.com/
How does Scala differ
              from Java?
                            • Pattern matching and
• Object oriented and         Extractors
  functional                • Actors
• Everything is an object   • XML literals
• First-class functions     • Properties
  (‘closures’)
                            • Case classes
• Singleton objects
                            • Lazy evaluation
• Mixin composition with
  Traits                    • Parser combinators
                            • Tuples
Statically Typed

Statically Typed    Dynamically Typed

                   Ruby, Python, Groovy,
  Java, Scala
                         JavaScript
Dynamic typing in JavaScript

> function calc(x) { return ((x + 2) * 2) }
undefined

> calc(1)
6

> calc("1")
24
Dynamic typing in Groovy

groovy:000> def calc(x) { ((x + 2) * 2) }
===> true

groovy:000> calc(1)
===> 6

groovy:000> calc("1")
===> 1212
Static Typing in Scala
scala> def calc(x:Int) = ((x + 2) * 2)
calc: (x: Int)Int

scala> calc(1)
res0: Int = 6

scala> calc("1")
<console>:6: error: type mismatch;
 found : java.lang.String("1")
 required: Int
    calc("1")
         ^
Static Typing in Scala
scala> def calc(x:Any) = x match {
  |       case y:Int => ((y + 2) * 2)
  |       case y:String => ((y + 2) * 2)
  |     }
calc: (x: Any)Any

scala> calc(1)
res1: Any = 6

scala> calc("1")
res2: Any = 1212
Type inference
  va




     Date x = new Date();
Ja
  a




     val x = new Date
 al
Sc




     x: java.util.Date = Tue Jan 12 01:04:42 GMT 2010
  va
Ja




     List<Integer> y = new ArrayList<Integer>();
     Collections.addAll(y,1,2,3);
    a
 al




     val y = List(1,2,3)
Sc




     y: List[Int] = List(1, 2, 3)
Everything is an object


 “Answer = ” + 6 * 4

“Answer = ”.+(6.*(4))
Concise / first-class functions
  va


     String s = "Which are the longer words";
Ja



     Array<String> words = s.split(‘ ’);
     ArrayList<String> longWords = new ArrayList<String>();
     for (w in words) {
       if (w.size() > 3) longWords.add(w);
     }
     System.out.println(longWords);
  a
 al




     val s = "Which are the longer words"
Sc




     val longWords = s.split(‘ ’).filter( _.size > 3)
     println(longWords)
Pattern matching
scala> val words = List("three","words","first")
words: List[java.lang.String] = List(two, words, first)

scala> val List(x, y, z) = words.sort( (a,b) => a < b )
x: java.lang.String = first
y: java.lang.String = three
z: java.lang.String = words

scala> val (x :: _) = words.sort( _ < _ )
x: java.lang.String = first
Properties, getters and setters
  va

   public class Rect {
Ja



     private final int width;
     private final int height;

       public Rect(int width, int height) {
         this.width = width;




                                              a
         this.height = height;




                                              al
       }


                                        Sc
                                               case class Rect(width:Int, height:Int) {
       public int getWidth() {
         return this.width;                      def area = width * height
       }                                       }
       public int getHeight() {
         return this.height;
                                               val r = Rect(2,4)
       }
       public int area() {                     println(r.area)
         return this.width * this.height;
       }
   }
   …
   Rect r = new Rect(2,4);
   System.out.println(r.area());
Regular expressions and
                extractors
val Email = """([A-Za-z0-9._%-]+)@([A-Za-z0-9.-]+.[A-Za-z]{2,4})""".r
val Telephone = """+(d+) ([d ]+)""".r

val inputs = List("+44 2423 1313", "test@gmail.co.uk", "Fred Bloggs")

inputs.foreach{ input =>
  val output = input match {
    case Email(user, domain) => "Email => User:" + user + " Domain:" + domain
    case Telephone(country, code) => "Telephone => Country:" + country + " Code:" + code
    case _ => "Unknown"
  }
  println(output)
}

Telephone => Country:44 Code:2423 1313
Email => User:test Domain:gmail.co.uk
Unknown
XML literals and parsing
val xml = <item>
      <title>Lift Version 1.0 Released</title>
      <link>http://www.scala-lang.org/node/1011</link>
      <description>Twelve is &gt; six</description>
      <comments>http://www.scala-lang.org/node/1011#comments</comments>
      <category domain="http://www.scala-lang.org/taxonomy/term/15">Featured</category>
      <pubDate>Fri, 27 Feb 2009 10:02:55 +0000</pubDate>
      <dc:creator>bagwell</dc:creator>
      <guid isPermaLink="false">1011 at http://www.scala-lang.org</guid>
     </item>
xml: scala.xml.Elem = …
(xml  "description").text
res1: String = Twelve is > six
(xml  "category"  "@domain" ).text
res2: String = http://www.scala-lang.org/taxonomy/term/15
Further XML file parsing +
import xml.XML

val loadnode = XML.loadFile(“input.xml”)

println(“Number of items = ” + (loadnode 
   “item”).toList.size)
Number of items = 2

val authors = (loadnode  “item”  “creator”).toList.map
    (_.text ).toSet.toList.sort(_<_)
println(“Authors were: ” + authors.mkString(“, ”))
Authors were: admin, bagwell
Commercial users of Scala
• Twitter—Scala back end Ruby front end
• LinkedIn
• Foursquare—Scala and Lift
• Siemens—Scala and Lift
• SAP
• EDF
• Sony Pictures (ImageWorks)
• Nature Magazine
• …and Google
Questions?
Scala @ TechMeetup Edinburgh

Weitere ähnliche Inhalte

Was ist angesagt?

Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008
Yardena Meymann
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
pramode_ce
 
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scala
akuklev
 

Was ist angesagt? (20)

Scale up your thinking
Scale up your thinkingScale up your thinking
Scale up your thinking
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
From Ruby to Scala
From Ruby to ScalaFrom Ruby to Scala
From Ruby to Scala
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Metaprogramming  in Scala 2.10, Eugene Burmako, Metaprogramming  in Scala 2.10, Eugene Burmako,
Metaprogramming in Scala 2.10, Eugene Burmako,
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
 
55 New Features in Java 7
55 New Features in Java 755 New Features in Java 7
55 New Features in Java 7
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 
Introduction to Spark SQL and Catalyst / Spark SQLおよびCalalystの紹介
Introduction to Spark SQL and Catalyst / Spark SQLおよびCalalystの紹介Introduction to Spark SQL and Catalyst / Spark SQLおよびCalalystの紹介
Introduction to Spark SQL and Catalyst / Spark SQLおよびCalalystの紹介
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
 
All about scala
All about scalaAll about scala
All about scala
 
Scala test
Scala testScala test
Scala test
 
Scala in Practice
Scala in PracticeScala in Practice
Scala in Practice
 
Solid And Sustainable Development in Scala
Solid And Sustainable Development in ScalaSolid And Sustainable Development in Scala
Solid And Sustainable Development in Scala
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
 
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scala
 

Andere mochten auch

Subversive talk - Eclipse Summit Europe 2008
Subversive talk - Eclipse Summit Europe 2008Subversive talk - Eclipse Summit Europe 2008
Subversive talk - Eclipse Summit Europe 2008
guestee71f
 
Scala2.8への移行
Scala2.8への移行Scala2.8への移行
Scala2.8への移行
guest5f4320
 
Buildstore Pres Lorraine
Buildstore Pres LorraineBuildstore Pres Lorraine
Buildstore Pres Lorraine
spikeytrim
 

Andere mochten auch (12)

Subversive talk - Eclipse Summit Europe 2008
Subversive talk - Eclipse Summit Europe 2008Subversive talk - Eclipse Summit Europe 2008
Subversive talk - Eclipse Summit Europe 2008
 
Refactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 RecapRefactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 Recap
 
如何在 Java App 中導入 Scala
如何在 Java App 中導入 Scala如何在 Java App 中導入 Scala
如何在 Java App 中導入 Scala
 
camel-scala.pdf
camel-scala.pdfcamel-scala.pdf
camel-scala.pdf
 
Scala2.8への移行
Scala2.8への移行Scala2.8への移行
Scala2.8への移行
 
A Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to ScalaA Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to Scala
 
Buildstore Pres Lorraine
Buildstore Pres LorraineBuildstore Pres Lorraine
Buildstore Pres Lorraine
 
Blogger2008
Blogger2008Blogger2008
Blogger2008
 
Dove Evolution
Dove EvolutionDove Evolution
Dove Evolution
 
Mangiare bene fa male e 21 marzo 2012 light
Mangiare bene fa male e 21 marzo 2012 lightMangiare bene fa male e 21 marzo 2012 light
Mangiare bene fa male e 21 marzo 2012 light
 
Onnivori vegetariani vegani il dibattito è aperto 19 aprile 2012
Onnivori vegetariani vegani il dibattito è aperto 19 aprile 2012Onnivori vegetariani vegani il dibattito è aperto 19 aprile 2012
Onnivori vegetariani vegani il dibattito è aperto 19 aprile 2012
 
Metsloomad
MetsloomadMetsloomad
Metsloomad
 

Ähnlich wie Scala @ TechMeetup Edinburgh

(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
Tomasz Wrobel
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
Introduction aux Macros
Introduction aux MacrosIntroduction aux Macros
Introduction aux Macros
univalence
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
shinolajla
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 
Pragmatic Real-World Scala
Pragmatic Real-World ScalaPragmatic Real-World Scala
Pragmatic Real-World Scala
parag978978
 

Ähnlich wie Scala @ TechMeetup Edinburgh (20)

Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
Scala on Android
Scala on AndroidScala on Android
Scala on Android
 
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
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
 
Introduction aux Macros
Introduction aux MacrosIntroduction aux Macros
Introduction aux Macros
 
Intro to Scala.js - Scala UG Cologne
Intro to Scala.js - Scala UG CologneIntro to Scala.js - Scala UG Cologne
Intro to Scala.js - Scala UG Cologne
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Short intro to scala and the play framework
Short intro to scala and the play frameworkShort intro to scala and the play framework
Short intro to scala and the play framework
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Pragmatic Real-World Scala
Pragmatic Real-World ScalaPragmatic Real-World Scala
Pragmatic Real-World Scala
 

Kürzlich hochgeladen

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Kürzlich hochgeladen (20)

08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 

Scala @ TechMeetup Edinburgh

  • 1. Scala @ TechMeetup Edinburgh Stuart Roebuck stuart.roebuck@proinnovate.com
  • 2. What does ProInnovate do? TOP SECRET
  • 3. The basics… • Scala stands for ‘scalable language’ • Scala runs on the Java Virtual Machine ( JVM) • Created by Martin Odersky (EPFL) • he previously created the Pizza language with Philip Wadler (now at Edinburgh University) • …then GJ (Generic Java) that became Java Generics in the official Java 5.0 release for which he apologises!
  • 4. How long has it been around? • Scala 1.0 appeared in 2003 • Scala 2.0 appeared in 2006 • Scala 2.7.7 is the current stable release • Scala 2.8 beta 1 is due for release any day now!
  • 5. “If I were to pick a language to use today other than Java, it would be Scala” James Gosling
  • 6. Try this at home! • Scala home: http://www.scala-lang.org/ • Downloadable for Mac, Linux & Windows • Shell interpreter: scala • Compilers: scalac and fsc • Documentation generator scaladoc • Plugins for Eclipse, Netbeans, IntelliJ
  • 7. Hello World! ->scala Welcome to Scala version 2.7.7.final (Java HotSpot (TM) 64-Bit Server VM, Java 1.6.0_17). Type in expressions to have them evaluated. Type :help for more information. scala> def main { println("Hello World!") } main: Unit scala> main Hello World!
  • 8. Build tools + • Maven Plugin (no endorsement implied)—http:// scala-tools.org/mvnsites/maven-scala-plugin/ • simple-build-tool—http://code.google.com/p/ simple-build-tool/ • Apache Ant tasks for Scala—http://www.scala- lang.org/node/98 • Apache Buildr—http://buildr.apache.org/ • JavaRebel—http://www.zeroturnaround.com/
  • 9. How does Scala differ from Java? • Pattern matching and • Object oriented and Extractors functional • Actors • Everything is an object • XML literals • First-class functions • Properties (‘closures’) • Case classes • Singleton objects • Lazy evaluation • Mixin composition with Traits • Parser combinators • Tuples
  • 10. Statically Typed Statically Typed Dynamically Typed Ruby, Python, Groovy, Java, Scala JavaScript
  • 11. Dynamic typing in JavaScript > function calc(x) { return ((x + 2) * 2) } undefined > calc(1) 6 > calc("1") 24
  • 12. Dynamic typing in Groovy groovy:000> def calc(x) { ((x + 2) * 2) } ===> true groovy:000> calc(1) ===> 6 groovy:000> calc("1") ===> 1212
  • 13. Static Typing in Scala scala> def calc(x:Int) = ((x + 2) * 2) calc: (x: Int)Int scala> calc(1) res0: Int = 6 scala> calc("1") <console>:6: error: type mismatch; found : java.lang.String("1") required: Int calc("1") ^
  • 14. Static Typing in Scala scala> def calc(x:Any) = x match { | case y:Int => ((y + 2) * 2) | case y:String => ((y + 2) * 2) | } calc: (x: Any)Any scala> calc(1) res1: Any = 6 scala> calc("1") res2: Any = 1212
  • 15. Type inference va Date x = new Date(); Ja a val x = new Date al Sc x: java.util.Date = Tue Jan 12 01:04:42 GMT 2010 va Ja List<Integer> y = new ArrayList<Integer>(); Collections.addAll(y,1,2,3); a al val y = List(1,2,3) Sc y: List[Int] = List(1, 2, 3)
  • 16. Everything is an object “Answer = ” + 6 * 4 “Answer = ”.+(6.*(4))
  • 17. Concise / first-class functions va String s = "Which are the longer words"; Ja Array<String> words = s.split(‘ ’); ArrayList<String> longWords = new ArrayList<String>(); for (w in words) { if (w.size() > 3) longWords.add(w); } System.out.println(longWords); a al val s = "Which are the longer words" Sc val longWords = s.split(‘ ’).filter( _.size > 3) println(longWords)
  • 18. Pattern matching scala> val words = List("three","words","first") words: List[java.lang.String] = List(two, words, first) scala> val List(x, y, z) = words.sort( (a,b) => a < b ) x: java.lang.String = first y: java.lang.String = three z: java.lang.String = words scala> val (x :: _) = words.sort( _ < _ ) x: java.lang.String = first
  • 19. Properties, getters and setters va public class Rect { Ja private final int width; private final int height; public Rect(int width, int height) { this.width = width; a this.height = height; al } Sc case class Rect(width:Int, height:Int) { public int getWidth() { return this.width; def area = width * height } } public int getHeight() { return this.height; val r = Rect(2,4) } public int area() { println(r.area) return this.width * this.height; } } … Rect r = new Rect(2,4); System.out.println(r.area());
  • 20. Regular expressions and extractors val Email = """([A-Za-z0-9._%-]+)@([A-Za-z0-9.-]+.[A-Za-z]{2,4})""".r val Telephone = """+(d+) ([d ]+)""".r val inputs = List("+44 2423 1313", "test@gmail.co.uk", "Fred Bloggs") inputs.foreach{ input => val output = input match { case Email(user, domain) => "Email => User:" + user + " Domain:" + domain case Telephone(country, code) => "Telephone => Country:" + country + " Code:" + code case _ => "Unknown" } println(output) } Telephone => Country:44 Code:2423 1313 Email => User:test Domain:gmail.co.uk Unknown
  • 21. XML literals and parsing val xml = <item> <title>Lift Version 1.0 Released</title> <link>http://www.scala-lang.org/node/1011</link> <description>Twelve is &gt; six</description> <comments>http://www.scala-lang.org/node/1011#comments</comments> <category domain="http://www.scala-lang.org/taxonomy/term/15">Featured</category> <pubDate>Fri, 27 Feb 2009 10:02:55 +0000</pubDate> <dc:creator>bagwell</dc:creator> <guid isPermaLink="false">1011 at http://www.scala-lang.org</guid> </item> xml: scala.xml.Elem = … (xml "description").text res1: String = Twelve is > six (xml "category" "@domain" ).text res2: String = http://www.scala-lang.org/taxonomy/term/15
  • 22. Further XML file parsing + import xml.XML val loadnode = XML.loadFile(“input.xml”) println(“Number of items = ” + (loadnode “item”).toList.size) Number of items = 2 val authors = (loadnode “item” “creator”).toList.map (_.text ).toSet.toList.sort(_<_) println(“Authors were: ” + authors.mkString(“, ”)) Authors were: admin, bagwell
  • 23. Commercial users of Scala • Twitter—Scala back end Ruby front end • LinkedIn • Foursquare—Scala and Lift • Siemens—Scala and Lift • SAP • EDF • Sony Pictures (ImageWorks) • Nature Magazine • …and Google
  • 24.
  • 25.
  • 26.