SlideShare a Scribd company logo
A brief Scala introduction… Or – LoveGame in 4 lines of code… Move over Java, here comes Scala…
Some questions… Please ask questions if you are curious! – Interactive conversation! 43 slides and counting – less than two minutes per slide, so we’ll be lucky! Just how keen are you? Who knows or has used a functional language before? Who has heard of Scala? Erlang, Lisp, Scheme? Who knows what a POM is? (not pom poms ;) I had tried out Groovy (Grails ++) but… I kept hearing something called Scala mentioned with a lot of respect, wanted to give it a go, just needed an excuse!
Quick love game run through Who knows what the love game is? Going to demonstrate the language through writing an algorithm Demonstrate on the board
The Love Game We will start off by going over the Love Game java pseudo code… ( I actually had trouble fitting it all onto the slide…!!)
Java - LoveGame DISPLAY argument 0 + “ “ + argument 1 + “ “ + argument 2 + “ “ + argument 3 + “ “ + argument 4 FORMAT bothNames = argument 0 + argument 1 + argument 3 + argument 4 CHANGE bothNames toLowerCase() FORMAT compWord = argument 2 CHANGE compWord toLowerCase() //Creates two character arrays to enable comparison. CHANGE FORMAT bothNames to character array bothNamesArray CHANGE FORMAT compWord to character array compWordArray //Creates an Integer array to store count results FORMAT Integer Array tallyArray = new Integer Array [compWord.length] FORMAT tallyArrayPointer = 0 FORMAT matchCounter = 0 //While loop counts the occurrences of each letter. PROCESS WHILE tallyArrayPointer  is less than compWord.length PROCESS FOR i = 0 ; i is less than bothNames.length; increment i FORMAT char nameLetter = element i in array bothNamesArray FORMAT compLetter = element tallyArrayPointer in array compWordArray IF nameLetter = compLetter THEN increment matchCounter ENDIF tallyArray[tallyArrayPointer] = matchCounter END FOR RESET matchCounter INCREMENT tallyArrayPointer END WHILE
Java – LoveGame 2 DECLARE tallyCounter DECLARE totalAdder //Calculates the percentage compatibility by taking consecutive elements in the array and  //adding them together. PROCESS WHILE the third element of tallyArray is not equal to -1 RESET tallyCounter PROCESS WHILE tallyCounter is less than length of tallyArray -1 &  tallyArray[tallyCounter+1] is not equal to -1 totalAdder = tallyArray[tallyCounter] + tallyArray[tallyCounter + 1] tallyArray[tallyCounter] = totalAdder INCREMENT tallyCounter END WHILE tallyArray[tallyCounter] = -1 END WHILE DECLARE finalPercentage = (1st element of tallyArray + 2nd element of tallyArray) * 2 DISPLAY Calculated compatibility = finalPercentage %
Scala - LoveGame Most of this improvement is due to being able to write in a functional manner vs the imperative style of looping and state manipulation We will now elaborate… The Love Game in 4 lines of code… var   loves  =  "loves" . toList   map (  x  =>  "roger federer maria sharapova" . toList   count ( x   ==  _ )) while (loves . length   >  1) loves =   loves   zip ( loves   tail )  map  { x  =>  x . _1   +   x . _2 } println ( "3 line compatibility = "   +   loves . head   *  2  +   " %" )
History Scala was created at the  École Polytechnique Fédérale de Lausanne  (EPFL) in 2001 by  Martin Odersky .  It was released publicly on the  Java platform  in January 2004, and on the .NET platform in June the same year. A second version of the language was released in March 2006. General purpose  Express common programming patterns in a  concise ,  elegant , and  type-safe  way Stands for “scalable language.”  Designed to grow with the demands of its users.  Wide range of programming tasks, from small scripts to building large systems. Smoothly  integrates features of object-oriented and functional languages.  Interoperable  with  Java . Both ways. Aims to make the most common case, easy. It is both a scripting language and a compiled one. Imutability and lack of side effects are key to distributed paralleism which are features of functional languages - a modern issue facing IT today with multi core process. So - compatibility, brevity, high-level abstractions
Woah. (Scala Features) Scala is object-oriented  Everything is an object! every value, even primitives, are an object Every function is an object Most operators are actually methods! (operator overloading) 2 * (4 + 6)  is actually compiled to (4.+(6)).*(2) Types and behaviour of objects are described by  classes  and  traits Multiple inheritance solution with mixins of traits Strong type system – type inference, generics singleton objects,  Traits Uniform access principle - “…client code should not be affected by a decision to implement some attribute as a field or as a method.”
Woah. (Scala Features) Scala is functional  every function is a value   Higher-order functions Anonymous functions Function  currying  / partial functions (multiple parameter lists) Lazy evaluation Infinite ranges built-in support for  pattern matching
Woah. (Scala Features) Scala is statically typed Not dynamic – No speed trade off’s (Compared to Groovy and Ruby), but less flexible at runtime (can be argued either way) But - Local type inference mechanism – don’t need to specify types if they can be inferred Generics (parameterised types) Scala is extensible (scalable) Implicit type conversions Allows language extensions - empowers you to create new language constructs The much beloved “Pimp my Library pattern”  Unique combination of language mechanisms makes it easy to smoothly add new language constructs in the form of libraries Interoperates with Java and .NET (.NET support is ‘rough’ atm) Optional semi colons, often option parenthesis and ‘dots’ Built in language support for XML processing through natural extention of pattern matching Great community Active mailing list – Martin himself replied to my query about Regex Parsers
Recursive version For demonstration purposes, we will work with my original recursive (slightly longer) version val   initialList  =  "loves" . toList . map (  x  =>  "roger federer maria sharapova" . toList . count ( x   ==  _ )) def   loveReduce ( numbers : List [ Int ]): Int  =  numbers   match  {  case   head   ::   Nil  =>  head   *  2 case  _ =>  loveReduce ( numbers . zip ( numbers . tail ). map { case  ( a ,  b ) =>  a + b }) }  println ( "Compatibility = "   +   loveReduce ( initialList )  +   " %" )
Line by line… The Map Function and Higher-Order Functions val initialList =  "loves" .toList.map(  F(x)  ) [ 1, 2, 3, 4] F(x)  ------  [ f(1), f(2), f(3), f(4) ] If F(x) = x^2 we get : [ f(1), f(4), f(9), f(16) ] F(x) =  "roger federer maria sharapova" .toList.count(  H(y,x)  ) H(y,x) = y == x val initialList =  "loves" .toList.map(  x  =>  "roger federer maria sharapova" .toList.count(  y => y  == x ))
Method Signatures public   int  loveReduce(List<Integer> numbers) {…} def   loveReduce (…)… def   loveReduce ( numbers : List [ Int ]): Int … (Need to specify return type only for recursive functions, otherwise the compiler invokes the type inference mechanism) def   loveReduce ( numbers : List [ Int ]): Int  =  numbers   match  {…} Don’t need surrounding braces as it’s a single statement
Recall – Java Case statements // checks if a number between 1 and 10 is prime int  number = 4; switch   ( number )   { case   1 :   return   true ; case   2 :   return   true ; case   3 :   return   true ; case   5 :   return   true ; case   7 :   return   true ; default :   return   false ; }
Recall – Java Case statements If each case statement doesn’t return, need to also include break statements to prevent unwanted fall through switch   ( number )   { case   1 :   object . operation1 ( number ); break ; case   2 :   object . operation2 ( number ); break ; case   3 :   object . operation3 ( number ); break ; case   5 :   object . operation4 ( number ); break ; case   7 :   object . operation5 ( number ); break ; default :   object.defaultOp ( number ); }
Pattern Matching in Scala – Java case statements on steroids Generalised form of case statement But more powerfull  No ‘fall through’ (common case) // checks if a number between 1 and 10 is prime number   match   { case   1   =>   return   true; case   2   =>   return   true; case   3   =>   return   true; case   5   =>   return   true; case   7   =>   return   true; case   _   =>   return   false;   //similar to Java’s default case }
Case statements in Scala But we can do better… Drop the semicolons, of course Drop the return statements Again, scala’s type inference kicks in – return value of function is simply last resolved statement // checks if a number between 1 and 10 is prime number   match   { case   1   =>   true case   2   =>   true case   3   =>   true case   5   =>   true case   7   =>   true case   _   =>   false } Clean eh?
Pattern matching List constructor – the ‘cons’ notation – “::” head :: tail  // matches 1 or more (can also use foo :: bar ) foo :: 2  // 2 element list where 2nd element is integer 2 head :: Nil  // Nil (is an object – extends List) represents an empty list – matches 1 element list x :: xs  // matches 1 or more Nil and :: are  actually  case  Classes! remember, there is nearly no restriction on characters used for class and method names etc Any method which takes a single parameter can be used as an infix operator – but :: (cons) when used in pattern matching is a special case That is, the infix operator “::” here, is treated as a constructor pattern  ::(foo, bar) From scala-lang.org:  Case classes are regular classes which export their constructor parameters and which provide a recursive decomposition mechanism via  pattern matching .  Checks the entire tree of the objects match Can do things like:  case   Foo ( x ,  Bar ( y ))  if   x   ==   y  =>  true numbers   match  {  case   head   ::   Nil  =>  head   *  2 case  _  => {…} }
Recursion in Functional Scala Who can describe what a recursive function is? Recursion in computer programming  defines a function in terms of itself.  Recursion:  *see Recursion . def   loveReduce ( ... )...{  ... ...  loveReduce ( g(x) ) }
Our reduce function For g(x) we need to return a list one element smaller in order for our recursion to work (i.e.  reduce ) Step 1 numbers.zip(numbers.tail) Step 2 .map{ x   =>  x._1 + x._2  } Nicer syntax – using a match expresion in place of a function literal .map{ case (a,b)   =>  a + b  } “ A match expression can be used anywhere a function literal can be used. Essentially, a match expression is a function literal, only more general.”
Recursion in Functional Scala loveReduce(numbers.zip(numbers.tail) .map{ case   (a,   b)   =>   a+b}) Each call, calls loveReduce, with a list one element smaller (due to the zip call)
Putting it all together -> Recursion def   loveReduce ( numbers :List [ Int ]) :Int   =   numbers   match   {   case   head   ::   Nil   =>   head   *   2 case   _   =>   loveReduce ( numbers . zip ( numbers . tail ) . map { case   ( a ,   b )   =>   a + b }) }   NB: Don’t need surrounding curly braces because it’s a single statement
Java - LoveGame DISPLAY argument 0 + “ “ + argument 1 + “ “ + argument 2 + “ “ + argument 3 + “ “ + argument 4 FORMAT bothNames = argument 0 + argument 1 + argument 3 + argument 4 CHANGE bothNames toLowerCase() FORMAT compWord = argument 2 CHANGE compWord toLowerCase() //Creates two character arrays to enable comparison. CHANGE FORMAT bothNames to character array bothNamesArray CHANGE FORMAT compWord to character array compWordArray //Creates an Integer array to store count results FORMAT Integer Array tallyArray = new Integer Array [compWord.length] FORMAT tallyArrayPointer = 0 FORMAT matchCounter = 0 //While loop counts the occurrences of each letter. PROCESS WHILE tallyArrayPointer  is less than compWord.length PROCESS FOR i = 0 ; i is less than bothNames.length; increment i FORMAT char nameLetter = element i in array bothNamesArray FORMAT compLetter = element tallyArrayPointer in array compWordArray IF nameLetter = compLetter THEN increment matchCounter ENDIF tallyArray[tallyArrayPointer] = matchCounter END FOR RESET matchCounter INCREMENT tallyArrayPointer END WHILE DECLARE tallyCounter DECLARE totalAdder //Calculates the percentage compatibility by taking consecutive elements in the array and  //adding them together. PROCESS WHILE the third element of tallyArray is not equal to -1 RESET tallyCounter PROCESS WHILE tallyCounter is less than length of tallyArray -1 &  tallyArray[tallyCounter+1] is not equal to -1 totalAdder = tallyArray[tallyCounter] + tallyArray[tallyCounter + 1] tallyArray[tallyCounter] = totalAdder INCREMENT tallyCounter END WHILE tallyArray[tallyCounter] = -1 END WHILE DECLARE finalPercentage = (1st element of tallyArray + 2nd element of tallyArray) * 2 DISPLAY Calculated compatibility = finalPercentage %
Scala - LoveGame Note the optional ‘.’ notation Which do you think will be easier to maintain? Any questions? The Love Game in 4 lines of code… var   loves   =   &quot;loves&quot; . toList   map (   x   =>   &quot;roger federer maria sharapova&quot; . toList   count ( x   ==   _   )) while   ( loves . length   >   1 ) loves   =   loves   zip ( loves   tail )   map   { x   =>   x . _1   +   x . _2 } println ( &quot;3 line compatibility = &quot;   +   loves . head   *   2   +   &quot; %&quot; )
For the cynics out there… smaller Java implementation public   static   int   loveMatch ( String   name1 ,   String   name2 ,   String   compWord )   {   int   []   tally   =   new   int [ compWord . length ()]; for   ( char   c   :   ( name1   +   name2 ). toCharArray ()) for   ( int   t   =   0 ;   t   <   tally . length ;   t ++) if   ( c   ==   compWord . charAt ( t ))   tally [ t ]++;   for   ( int   i   =   tally . length   -   1 ;   i   >=   0 ;   i --) for   ( int   j   =   0 ;   j   <   i ;   j ++) tally [ j ]   +=   tally [ j   +   1 ]; return   tally [ 0 ]   *   2 ; }
And for the side ball…. C#.NET LINQ var   loves   =  “ loves ” . Select ( x   =>  “ roger   federer   maria   sharapova ” . Count ( c   =>   x   ==   c )). ToList (); while   ( loves . Count   >   1 ) loves   =   Enumerable . Range ( 0 ,   loves . Count   -   1 ). Select ( i   =>   loves [ i ]   +   loves [ i   +  1 ]). ToList (); Console . WriteLine ( loves . Single ()   *   2 );
More Scala to come… Pimp my library! Implicit conversion functions Examples: MyRichString E.g. JScience interface Measure   length  =  Measure .valueOf(50,  SI .CENTI( SI .METER)).plus( Measure .valueOf(25.0,  SI .METER));  Measure   lengthInCentimeters  =  length .to( SI .CENTI( SI .METER));  System.out .println ( &quot;length in centimeters is &quot;  + lengthInCentimeters.getEstimatedValue()); VS var len =  50 .centimeters +  25 .meters    println(&quot; length in centimeters is  &quot; + len)  
More Scala to come… Class properties VS instance variables Static? Currying the technique of transforming a  function  that takes multiple  arguments  into a function that takes a single argument (the other arguments having been specified by the curry).  Advanced Pattern Matching and Case Classes Actors Library concurrent processes that communicate by exchanging messages.
Combinator Parsing Define language parsers out of context free grammar definitions 8 * ( 4 + 2 )  expr ::= term { '+' term | ‘-’ term}. term ::= factor { '*' factor | '/' factor}. factor ::= numericLit | '(' expr ')'.
Combinator Parsing object   ArithmeticParsers   extends   StandardTokenParsers   {   lexical . delimiters   ++=   List ( &quot;(&quot; ,   &quot;)&quot; ,   &quot;+&quot; ,   &quot;-&quot; ,   &quot;*&quot; ,   &quot;/&quot; ) def   expr :   Parser [ Any ]   =   term   ~   rep ( &quot;+&quot;   ~   term   |   &quot;-&quot;   ~   term ) def   term   =   factor   ~   rep ( &quot;*&quot;   ~   factor   |   &quot;/&quot;   ~   factor ) def   factor :   Parser [ Any ]   =   &quot;(&quot;   ~   expr   ~   &quot;)&quot;   |   numericLit } val   tokens   =   new   lexical . Scanner ( args ( 0 )) println ( args ( 0 )) println ( phrase ( expr )( tokens )) This of course also parses ( 36 / 8 * ( 4 + 2 ) ) / ( ( 5 – 3 ) * 6 )
Combinator Parsing More complex and practical example: (buy 100 IBM shares at max USD 45, sell 50 CISCO shares at min USD 25, buy 100 Google shares at max USD 800) for trading_account &quot;SSS1234&quot;   http://debasishg.blogspot.com/2008/04/external-dsls-made-easy-with-scala.html
Combinator Parsing // ClientOrder.java public   class   ClientOrder   { public   enum   BuySell   { BUY , SELL } private   String   accountNo ; private   List < LineItem >   lineItems   =   new   ArrayList < LineItem >(); // LineItem.java public   class   LineItem   { private   final   String   security ; private   final   int   quantity ; private   final   ClientOrder . BuySell   bs ; private   final   int   price ; public   LineItem ( String   security ,   int   quantity ,   ClientOrder . BuySell   bs ,   int   price )   { this . security   =   security ; this . quantity   =   quantity ; this . bs   =   bs ; this . price   =   price ;
Properties / Class Parameters Scala’s concise syntax this is Java class   MyClass   { private   int   index ; private   String   name ; public   MyClass ( int   index ,   String   name )   { this . index   =   index ; this . name   =   name ; } } In Scala, you would likely write this instead: class   MyClass ( index :   Int ,   name :   String )
Implicit Conversions (and mixins with traits) class MyRichString (str: String ) {   def countOccurances (haystack: String) =  str.toList.map( x => haystack.toList.count(x == _ )) } trait MyConversions  { implicit def string2MyRichString (str: String) = new MyRichString(str) } object MyConversionsTest extends Application with MyConversions  { val m  = &quot;cow&quot; println(m.countOccurances(&quot;o&quot;)) }
Working with XML with language level support Consider the following XML document: <html> <head> <title> Hello XHTML world </title> </head> <body> <h1> Hello world </h1> <p><a   href = &quot;http://scala-lang.org/&quot; > Scala </a>  talks XHTML </p> </body> </html>
Working with XML with language level support This document can be created by the following Scala program: val page =  <html> <head> <title> Hello XHTML world </title> </head> <body> <h1> Hello world </h1> <p><a   href = &quot;scala-lang.org&quot; > Scala </a>  talks XHTML </p> </body> </html> ; println(page.toString())
Working with XML with language level support It is possible to mix Scala expressions and XML: object   XMLTest2   extends   Application   { import   scala . xml . _ val   df   =   java . text . DateFormat . getDateInstance () val   dateString   =   df . format ( new   java . util . Date ()) def   theDate ( name :   String )   =   < dateMsg   addressedTo ={   name   }> Hello ,   {   name   }!   Today   is   {   dateString   } </ dateMsg >; println ( theDate ( &quot;John Doe&quot; ). toString ()) }
Actors and Concurrency class   Ping ( count :   int ,   pong :   Actor )   extends   Actor   { def   act ()   { var   pingsLeft   =   count   -   1 pong   !   Ping while   ( true )   { receive   { case   Pong   => if   ( pingsLeft   %   1000   ==   0 ) Console . println ( &quot;Ping: pong&quot; ) if   ( pingsLeft   >   0 )   { pong   !   Ping pingsLeft   -=   1 }   else   { Console . println ( &quot;Ping: stop&quot; ) pong   !   Stop exit () } class   Pong   extends   Actor   { def   act ()   { var   pongCount   =   0 while   ( true )   { receive   { case   Ping   => if   ( pongCount   %   1000   ==   0 ) Console . println ( &quot;Pong: ping &quot; + pongCount ) sender   !   Pong pongCount   =   pongCount   +   1 case   Stop   => Console . println ( &quot;Pong: stop&quot; ) exit () val   pong   =   new   Pong val   ping   =   new   Ping ( 100000 ,   pong ) ping . start pong . start With the advent of multi-core processors concurrent programming is becoming indispensable.  Actors are basically concurrent processes that communicate by exchanging messages, instead of sharing state.
Companion objects and Static Singleton and Static considered harmful Static methods cannot be polymorphic Inheritance problems So - all static members are now grouped in their own ‘object’ Scala’s “companion ‘object’” (singleton object)
More and more and more…. Nested Functions By-name parameters Lazy evaluation Logging –  no more stupid ( if ( log.isEnabled() ) protection! ) Private packages LiftWeb (Rails/Grails like web app for Scala) The Option type – optional values –  Some or None First-class Properties coming… Properties are objects (OO sense) Govern access to a (possibly calculated) field.  Properties can have other methods in addition to get/set logic, such as registering event listeners.  Writing new control structures val   file   =   new   File ( &quot;date.txt&quot; ) withPrintWriter ( file )   { writer   =>   writer.println ( new   java.util.Date ) }
More Technologies are out there! Expand your mind! Online Ajax HelpRequestList program in 9 lines!! Groovy on Grails Maven the modular build system Connoisseur! Groovy Builder and G-Strings Groovy Command Line Interpreter Groovy Wicket builder Polygot programming a  computer program  or  script  written in a valid form of multiple  programming languages , which performs the same operations or output independently of the programming language used to compile or interpret it.  Git a distributed  revision control  /  software configuration management  project created by  Linus   Torvalds , initially for the  Linux kernel  development.
The Full Article Read the article at: http://stubbisms.wordpress.com/2008/02/22/my-foray-into-the-world-of-scala/ More Scala links scala-lang.org Thanks for listening!

More Related Content

PPT
Javascript
PPT
The JavaScript Programming Language
PPT
The Java Script Programming Language
PPT
Adv. python regular expression by Rj
PPT
16 Java Regex
PPTX
Regular expressions in Python
PPTX
Regular Expressions in Java
PDF
Utility Classes
Javascript
The JavaScript Programming Language
The Java Script Programming Language
Adv. python regular expression by Rj
16 Java Regex
Regular expressions in Python
Regular Expressions in Java
Utility Classes

What's hot (20)

PPTX
Java: Regular Expression
PDF
DEFUN 2008 - Real World Haskell
PDF
Real World Haskell: Lecture 7
PPT
Introduction to Python - Part Three
PPTX
Regular expressions
PDF
Real World Haskell: Lecture 1
PPT
Python
PPT
M C6java7
PDF
Pythonintro
PPTX
OCA Java SE 8 Exam Chapter 3 Core Java APIs
PDF
Kleisli Composition
PDF
Real World Haskell: Lecture 6
PDF
Real World Haskell: Lecture 3
PPT
M C6java3
PPTX
Intro to Scala
PPTX
Introduction to scala for a c programmer
PPTX
Python language data types
PPTX
PDF
Grep Introduction
PDF
Python Programming - XI. String Manipulation and Regular Expressions
Java: Regular Expression
DEFUN 2008 - Real World Haskell
Real World Haskell: Lecture 7
Introduction to Python - Part Three
Regular expressions
Real World Haskell: Lecture 1
Python
M C6java7
Pythonintro
OCA Java SE 8 Exam Chapter 3 Core Java APIs
Kleisli Composition
Real World Haskell: Lecture 6
Real World Haskell: Lecture 3
M C6java3
Intro to Scala
Introduction to scala for a c programmer
Python language data types
Grep Introduction
Python Programming - XI. String Manipulation and Regular Expressions
Ad

Similar to Scala Language Intro - Inspired by the Love Game (20)

PDF
Introducing Pattern Matching in Scala
PPTX
Scala, Play 2.0 & Cloud Foundry
PPT
Scala introduction
PPT
Scala presentation by Aleksandar Prokopec
ODP
Scala introduction
PPT
Rewriting Java In Scala
PDF
Introductiontoprogramminginscala
PPT
Scala presentationjune112011
ODP
Introduction To Scala
PDF
Programming in Scala - Lecture Three
PPTX
Introduction to Clojure and why it's hot for Sart-Ups
PDF
Programming in scala - 1
PDF
Scala Paradigms
ODP
PPTX
A Brief Intro to Scala
PDF
Scala for Java Programmers
PDF
What I learned from Seven Languages in Seven Weeks (IPRUG)
PDF
Pragmatic Real-World Scala
PDF
Pragmatic Real-World Scala (short version)
PDF
Live coding scala 'the java of the future'
Introducing Pattern Matching in Scala
Scala, Play 2.0 & Cloud Foundry
Scala introduction
Scala presentation by Aleksandar Prokopec
Scala introduction
Rewriting Java In Scala
Introductiontoprogramminginscala
Scala presentationjune112011
Introduction To Scala
Programming in Scala - Lecture Three
Introduction to Clojure and why it's hot for Sart-Ups
Programming in scala - 1
Scala Paradigms
A Brief Intro to Scala
Scala for Java Programmers
What I learned from Seven Languages in Seven Weeks (IPRUG)
Pragmatic Real-World Scala
Pragmatic Real-World Scala (short version)
Live coding scala 'the java of the future'
Ad

Recently uploaded (20)

PDF
WRN_Investor_Presentation_August 2025.pdf
PDF
COST SHEET- Tender and Quotation unit 2.pdf
PPTX
HR Introduction Slide (1).pptx on hr intro
DOCX
Business Management - unit 1 and 2
PPTX
Amazon (Business Studies) management studies
PPTX
Probability Distribution, binomial distribution, poisson distribution
PDF
A Brief Introduction About Julia Allison
PPTX
Lecture (1)-Introduction.pptx business communication
PDF
kom-180-proposal-for-a-directive-amending-directive-2014-45-eu-and-directive-...
PPTX
job Avenue by vinith.pptxvnbvnvnvbnvbnbmnbmbh
PPT
340036916-American-Literature-Literary-Period-Overview.ppt
PDF
IFRS Notes in your pocket for study all the time
DOCX
unit 1 COST ACCOUNTING AND COST SHEET
PDF
20250805_A. Stotz All Weather Strategy - Performance review July 2025.pdf
PDF
DOC-20250806-WA0002._20250806_112011_0000.pdf
PDF
Laughter Yoga Basic Learning Workshop Manual
PDF
Reconciliation AND MEMORANDUM RECONCILATION
PDF
How to Get Business Funding for Small Business Fast
PDF
Nidhal Samdaie CV - International Business Consultant
PDF
Outsourced Audit & Assurance in USA Why Globus Finanza is Your Trusted Choice
WRN_Investor_Presentation_August 2025.pdf
COST SHEET- Tender and Quotation unit 2.pdf
HR Introduction Slide (1).pptx on hr intro
Business Management - unit 1 and 2
Amazon (Business Studies) management studies
Probability Distribution, binomial distribution, poisson distribution
A Brief Introduction About Julia Allison
Lecture (1)-Introduction.pptx business communication
kom-180-proposal-for-a-directive-amending-directive-2014-45-eu-and-directive-...
job Avenue by vinith.pptxvnbvnvnvbnvbnbmnbmbh
340036916-American-Literature-Literary-Period-Overview.ppt
IFRS Notes in your pocket for study all the time
unit 1 COST ACCOUNTING AND COST SHEET
20250805_A. Stotz All Weather Strategy - Performance review July 2025.pdf
DOC-20250806-WA0002._20250806_112011_0000.pdf
Laughter Yoga Basic Learning Workshop Manual
Reconciliation AND MEMORANDUM RECONCILATION
How to Get Business Funding for Small Business Fast
Nidhal Samdaie CV - International Business Consultant
Outsourced Audit & Assurance in USA Why Globus Finanza is Your Trusted Choice

Scala Language Intro - Inspired by the Love Game

  • 1. A brief Scala introduction… Or – LoveGame in 4 lines of code… Move over Java, here comes Scala…
  • 2. Some questions… Please ask questions if you are curious! – Interactive conversation! 43 slides and counting – less than two minutes per slide, so we’ll be lucky! Just how keen are you? Who knows or has used a functional language before? Who has heard of Scala? Erlang, Lisp, Scheme? Who knows what a POM is? (not pom poms ;) I had tried out Groovy (Grails ++) but… I kept hearing something called Scala mentioned with a lot of respect, wanted to give it a go, just needed an excuse!
  • 3. Quick love game run through Who knows what the love game is? Going to demonstrate the language through writing an algorithm Demonstrate on the board
  • 4. The Love Game We will start off by going over the Love Game java pseudo code… ( I actually had trouble fitting it all onto the slide…!!)
  • 5. Java - LoveGame DISPLAY argument 0 + “ “ + argument 1 + “ “ + argument 2 + “ “ + argument 3 + “ “ + argument 4 FORMAT bothNames = argument 0 + argument 1 + argument 3 + argument 4 CHANGE bothNames toLowerCase() FORMAT compWord = argument 2 CHANGE compWord toLowerCase() //Creates two character arrays to enable comparison. CHANGE FORMAT bothNames to character array bothNamesArray CHANGE FORMAT compWord to character array compWordArray //Creates an Integer array to store count results FORMAT Integer Array tallyArray = new Integer Array [compWord.length] FORMAT tallyArrayPointer = 0 FORMAT matchCounter = 0 //While loop counts the occurrences of each letter. PROCESS WHILE tallyArrayPointer is less than compWord.length PROCESS FOR i = 0 ; i is less than bothNames.length; increment i FORMAT char nameLetter = element i in array bothNamesArray FORMAT compLetter = element tallyArrayPointer in array compWordArray IF nameLetter = compLetter THEN increment matchCounter ENDIF tallyArray[tallyArrayPointer] = matchCounter END FOR RESET matchCounter INCREMENT tallyArrayPointer END WHILE
  • 6. Java – LoveGame 2 DECLARE tallyCounter DECLARE totalAdder //Calculates the percentage compatibility by taking consecutive elements in the array and //adding them together. PROCESS WHILE the third element of tallyArray is not equal to -1 RESET tallyCounter PROCESS WHILE tallyCounter is less than length of tallyArray -1 & tallyArray[tallyCounter+1] is not equal to -1 totalAdder = tallyArray[tallyCounter] + tallyArray[tallyCounter + 1] tallyArray[tallyCounter] = totalAdder INCREMENT tallyCounter END WHILE tallyArray[tallyCounter] = -1 END WHILE DECLARE finalPercentage = (1st element of tallyArray + 2nd element of tallyArray) * 2 DISPLAY Calculated compatibility = finalPercentage %
  • 7. Scala - LoveGame Most of this improvement is due to being able to write in a functional manner vs the imperative style of looping and state manipulation We will now elaborate… The Love Game in 4 lines of code… var loves = &quot;loves&quot; . toList map ( x => &quot;roger federer maria sharapova&quot; . toList count ( x == _ )) while (loves . length > 1) loves = loves zip ( loves tail ) map { x => x . _1 + x . _2 } println ( &quot;3 line compatibility = &quot; + loves . head * 2 + &quot; %&quot; )
  • 8. History Scala was created at the École Polytechnique Fédérale de Lausanne (EPFL) in 2001 by Martin Odersky . It was released publicly on the Java platform in January 2004, and on the .NET platform in June the same year. A second version of the language was released in March 2006. General purpose Express common programming patterns in a concise , elegant , and type-safe way Stands for “scalable language.” Designed to grow with the demands of its users. Wide range of programming tasks, from small scripts to building large systems. Smoothly integrates features of object-oriented and functional languages. Interoperable with Java . Both ways. Aims to make the most common case, easy. It is both a scripting language and a compiled one. Imutability and lack of side effects are key to distributed paralleism which are features of functional languages - a modern issue facing IT today with multi core process. So - compatibility, brevity, high-level abstractions
  • 9. Woah. (Scala Features) Scala is object-oriented Everything is an object! every value, even primitives, are an object Every function is an object Most operators are actually methods! (operator overloading) 2 * (4 + 6) is actually compiled to (4.+(6)).*(2) Types and behaviour of objects are described by classes and traits Multiple inheritance solution with mixins of traits Strong type system – type inference, generics singleton objects, Traits Uniform access principle - “…client code should not be affected by a decision to implement some attribute as a field or as a method.”
  • 10. Woah. (Scala Features) Scala is functional every function is a value Higher-order functions Anonymous functions Function currying / partial functions (multiple parameter lists) Lazy evaluation Infinite ranges built-in support for pattern matching
  • 11. Woah. (Scala Features) Scala is statically typed Not dynamic – No speed trade off’s (Compared to Groovy and Ruby), but less flexible at runtime (can be argued either way) But - Local type inference mechanism – don’t need to specify types if they can be inferred Generics (parameterised types) Scala is extensible (scalable) Implicit type conversions Allows language extensions - empowers you to create new language constructs The much beloved “Pimp my Library pattern” Unique combination of language mechanisms makes it easy to smoothly add new language constructs in the form of libraries Interoperates with Java and .NET (.NET support is ‘rough’ atm) Optional semi colons, often option parenthesis and ‘dots’ Built in language support for XML processing through natural extention of pattern matching Great community Active mailing list – Martin himself replied to my query about Regex Parsers
  • 12. Recursive version For demonstration purposes, we will work with my original recursive (slightly longer) version val initialList = &quot;loves&quot; . toList . map ( x => &quot;roger federer maria sharapova&quot; . toList . count ( x == _ )) def loveReduce ( numbers : List [ Int ]): Int = numbers match { case head :: Nil => head * 2 case _ => loveReduce ( numbers . zip ( numbers . tail ). map { case ( a , b ) => a + b }) } println ( &quot;Compatibility = &quot; + loveReduce ( initialList ) + &quot; %&quot; )
  • 13. Line by line… The Map Function and Higher-Order Functions val initialList = &quot;loves&quot; .toList.map( F(x) ) [ 1, 2, 3, 4] F(x) ------  [ f(1), f(2), f(3), f(4) ] If F(x) = x^2 we get : [ f(1), f(4), f(9), f(16) ] F(x) = &quot;roger federer maria sharapova&quot; .toList.count( H(y,x) ) H(y,x) = y == x val initialList = &quot;loves&quot; .toList.map( x => &quot;roger federer maria sharapova&quot; .toList.count( y => y == x ))
  • 14. Method Signatures public int loveReduce(List<Integer> numbers) {…} def loveReduce (…)… def loveReduce ( numbers : List [ Int ]): Int … (Need to specify return type only for recursive functions, otherwise the compiler invokes the type inference mechanism) def loveReduce ( numbers : List [ Int ]): Int = numbers match {…} Don’t need surrounding braces as it’s a single statement
  • 15. Recall – Java Case statements // checks if a number between 1 and 10 is prime int number = 4; switch ( number ) { case 1 : return true ; case 2 : return true ; case 3 : return true ; case 5 : return true ; case 7 : return true ; default : return false ; }
  • 16. Recall – Java Case statements If each case statement doesn’t return, need to also include break statements to prevent unwanted fall through switch ( number ) { case 1 : object . operation1 ( number ); break ; case 2 : object . operation2 ( number ); break ; case 3 : object . operation3 ( number ); break ; case 5 : object . operation4 ( number ); break ; case 7 : object . operation5 ( number ); break ; default : object.defaultOp ( number ); }
  • 17. Pattern Matching in Scala – Java case statements on steroids Generalised form of case statement But more powerfull No ‘fall through’ (common case) // checks if a number between 1 and 10 is prime number match { case 1 => return true; case 2 => return true; case 3 => return true; case 5 => return true; case 7 => return true; case _ => return false; //similar to Java’s default case }
  • 18. Case statements in Scala But we can do better… Drop the semicolons, of course Drop the return statements Again, scala’s type inference kicks in – return value of function is simply last resolved statement // checks if a number between 1 and 10 is prime number match { case 1 => true case 2 => true case 3 => true case 5 => true case 7 => true case _ => false } Clean eh?
  • 19. Pattern matching List constructor – the ‘cons’ notation – “::” head :: tail // matches 1 or more (can also use foo :: bar ) foo :: 2 // 2 element list where 2nd element is integer 2 head :: Nil // Nil (is an object – extends List) represents an empty list – matches 1 element list x :: xs // matches 1 or more Nil and :: are actually case Classes! remember, there is nearly no restriction on characters used for class and method names etc Any method which takes a single parameter can be used as an infix operator – but :: (cons) when used in pattern matching is a special case That is, the infix operator “::” here, is treated as a constructor pattern ::(foo, bar) From scala-lang.org: Case classes are regular classes which export their constructor parameters and which provide a recursive decomposition mechanism via pattern matching . Checks the entire tree of the objects match Can do things like: case Foo ( x , Bar ( y )) if x == y => true numbers match { case head :: Nil => head * 2 case _ => {…} }
  • 20. Recursion in Functional Scala Who can describe what a recursive function is? Recursion in computer programming defines a function in terms of itself. Recursion: *see Recursion . def loveReduce ( ... )...{ ... ... loveReduce ( g(x) ) }
  • 21. Our reduce function For g(x) we need to return a list one element smaller in order for our recursion to work (i.e. reduce ) Step 1 numbers.zip(numbers.tail) Step 2 .map{ x => x._1 + x._2 } Nicer syntax – using a match expresion in place of a function literal .map{ case (a,b) => a + b } “ A match expression can be used anywhere a function literal can be used. Essentially, a match expression is a function literal, only more general.”
  • 22. Recursion in Functional Scala loveReduce(numbers.zip(numbers.tail) .map{ case (a, b) => a+b}) Each call, calls loveReduce, with a list one element smaller (due to the zip call)
  • 23. Putting it all together -> Recursion def loveReduce ( numbers :List [ Int ]) :Int = numbers match { case head :: Nil => head * 2 case _ => loveReduce ( numbers . zip ( numbers . tail ) . map { case ( a , b ) => a + b }) } NB: Don’t need surrounding curly braces because it’s a single statement
  • 24. Java - LoveGame DISPLAY argument 0 + “ “ + argument 1 + “ “ + argument 2 + “ “ + argument 3 + “ “ + argument 4 FORMAT bothNames = argument 0 + argument 1 + argument 3 + argument 4 CHANGE bothNames toLowerCase() FORMAT compWord = argument 2 CHANGE compWord toLowerCase() //Creates two character arrays to enable comparison. CHANGE FORMAT bothNames to character array bothNamesArray CHANGE FORMAT compWord to character array compWordArray //Creates an Integer array to store count results FORMAT Integer Array tallyArray = new Integer Array [compWord.length] FORMAT tallyArrayPointer = 0 FORMAT matchCounter = 0 //While loop counts the occurrences of each letter. PROCESS WHILE tallyArrayPointer is less than compWord.length PROCESS FOR i = 0 ; i is less than bothNames.length; increment i FORMAT char nameLetter = element i in array bothNamesArray FORMAT compLetter = element tallyArrayPointer in array compWordArray IF nameLetter = compLetter THEN increment matchCounter ENDIF tallyArray[tallyArrayPointer] = matchCounter END FOR RESET matchCounter INCREMENT tallyArrayPointer END WHILE DECLARE tallyCounter DECLARE totalAdder //Calculates the percentage compatibility by taking consecutive elements in the array and //adding them together. PROCESS WHILE the third element of tallyArray is not equal to -1 RESET tallyCounter PROCESS WHILE tallyCounter is less than length of tallyArray -1 & tallyArray[tallyCounter+1] is not equal to -1 totalAdder = tallyArray[tallyCounter] + tallyArray[tallyCounter + 1] tallyArray[tallyCounter] = totalAdder INCREMENT tallyCounter END WHILE tallyArray[tallyCounter] = -1 END WHILE DECLARE finalPercentage = (1st element of tallyArray + 2nd element of tallyArray) * 2 DISPLAY Calculated compatibility = finalPercentage %
  • 25. Scala - LoveGame Note the optional ‘.’ notation Which do you think will be easier to maintain? Any questions? The Love Game in 4 lines of code… var loves = &quot;loves&quot; . toList map ( x => &quot;roger federer maria sharapova&quot; . toList count ( x == _ )) while ( loves . length > 1 ) loves = loves zip ( loves tail ) map { x => x . _1 + x . _2 } println ( &quot;3 line compatibility = &quot; + loves . head * 2 + &quot; %&quot; )
  • 26. For the cynics out there… smaller Java implementation public static int loveMatch ( String name1 , String name2 , String compWord ) { int [] tally = new int [ compWord . length ()]; for ( char c : ( name1 + name2 ). toCharArray ()) for ( int t = 0 ; t < tally . length ; t ++) if ( c == compWord . charAt ( t )) tally [ t ]++; for ( int i = tally . length - 1 ; i >= 0 ; i --) for ( int j = 0 ; j < i ; j ++) tally [ j ] += tally [ j + 1 ]; return tally [ 0 ] * 2 ; }
  • 27. And for the side ball…. C#.NET LINQ var loves = “ loves ” . Select ( x => “ roger federer maria sharapova ” . Count ( c => x == c )). ToList (); while ( loves . Count > 1 ) loves = Enumerable . Range ( 0 , loves . Count - 1 ). Select ( i => loves [ i ] + loves [ i + 1 ]). ToList (); Console . WriteLine ( loves . Single () * 2 );
  • 28. More Scala to come… Pimp my library! Implicit conversion functions Examples: MyRichString E.g. JScience interface Measure length = Measure .valueOf(50, SI .CENTI( SI .METER)).plus( Measure .valueOf(25.0, SI .METER)); Measure lengthInCentimeters = length .to( SI .CENTI( SI .METER)); System.out .println ( &quot;length in centimeters is &quot; + lengthInCentimeters.getEstimatedValue()); VS var len =  50 .centimeters +  25 .meters   println(&quot; length in centimeters is  &quot; + len)  
  • 29. More Scala to come… Class properties VS instance variables Static? Currying the technique of transforming a function that takes multiple arguments into a function that takes a single argument (the other arguments having been specified by the curry). Advanced Pattern Matching and Case Classes Actors Library concurrent processes that communicate by exchanging messages.
  • 30. Combinator Parsing Define language parsers out of context free grammar definitions 8 * ( 4 + 2 ) expr ::= term { '+' term | ‘-’ term}. term ::= factor { '*' factor | '/' factor}. factor ::= numericLit | '(' expr ')'.
  • 31. Combinator Parsing object ArithmeticParsers extends StandardTokenParsers { lexical . delimiters ++= List ( &quot;(&quot; , &quot;)&quot; , &quot;+&quot; , &quot;-&quot; , &quot;*&quot; , &quot;/&quot; ) def expr : Parser [ Any ] = term ~ rep ( &quot;+&quot; ~ term | &quot;-&quot; ~ term ) def term = factor ~ rep ( &quot;*&quot; ~ factor | &quot;/&quot; ~ factor ) def factor : Parser [ Any ] = &quot;(&quot; ~ expr ~ &quot;)&quot; | numericLit } val tokens = new lexical . Scanner ( args ( 0 )) println ( args ( 0 )) println ( phrase ( expr )( tokens )) This of course also parses ( 36 / 8 * ( 4 + 2 ) ) / ( ( 5 – 3 ) * 6 )
  • 32. Combinator Parsing More complex and practical example: (buy 100 IBM shares at max USD 45, sell 50 CISCO shares at min USD 25, buy 100 Google shares at max USD 800) for trading_account &quot;SSS1234&quot; http://debasishg.blogspot.com/2008/04/external-dsls-made-easy-with-scala.html
  • 33. Combinator Parsing // ClientOrder.java public class ClientOrder { public enum BuySell { BUY , SELL } private String accountNo ; private List < LineItem > lineItems = new ArrayList < LineItem >(); // LineItem.java public class LineItem { private final String security ; private final int quantity ; private final ClientOrder . BuySell bs ; private final int price ; public LineItem ( String security , int quantity , ClientOrder . BuySell bs , int price ) { this . security = security ; this . quantity = quantity ; this . bs = bs ; this . price = price ;
  • 34. Properties / Class Parameters Scala’s concise syntax this is Java class MyClass { private int index ; private String name ; public MyClass ( int index , String name ) { this . index = index ; this . name = name ; } } In Scala, you would likely write this instead: class MyClass ( index : Int , name : String )
  • 35. Implicit Conversions (and mixins with traits) class MyRichString (str: String ) { def countOccurances (haystack: String) = str.toList.map( x => haystack.toList.count(x == _ )) } trait MyConversions { implicit def string2MyRichString (str: String) = new MyRichString(str) } object MyConversionsTest extends Application with MyConversions { val m = &quot;cow&quot; println(m.countOccurances(&quot;o&quot;)) }
  • 36. Working with XML with language level support Consider the following XML document: <html> <head> <title> Hello XHTML world </title> </head> <body> <h1> Hello world </h1> <p><a href = &quot;http://scala-lang.org/&quot; > Scala </a> talks XHTML </p> </body> </html>
  • 37. Working with XML with language level support This document can be created by the following Scala program: val page = <html> <head> <title> Hello XHTML world </title> </head> <body> <h1> Hello world </h1> <p><a href = &quot;scala-lang.org&quot; > Scala </a> talks XHTML </p> </body> </html> ; println(page.toString())
  • 38. Working with XML with language level support It is possible to mix Scala expressions and XML: object XMLTest2 extends Application { import scala . xml . _ val df = java . text . DateFormat . getDateInstance () val dateString = df . format ( new java . util . Date ()) def theDate ( name : String ) = < dateMsg addressedTo ={ name }> Hello , { name }! Today is { dateString } </ dateMsg >; println ( theDate ( &quot;John Doe&quot; ). toString ()) }
  • 39. Actors and Concurrency class Ping ( count : int , pong : Actor ) extends Actor { def act () { var pingsLeft = count - 1 pong ! Ping while ( true ) { receive { case Pong => if ( pingsLeft % 1000 == 0 ) Console . println ( &quot;Ping: pong&quot; ) if ( pingsLeft > 0 ) { pong ! Ping pingsLeft -= 1 } else { Console . println ( &quot;Ping: stop&quot; ) pong ! Stop exit () } class Pong extends Actor { def act () { var pongCount = 0 while ( true ) { receive { case Ping => if ( pongCount % 1000 == 0 ) Console . println ( &quot;Pong: ping &quot; + pongCount ) sender ! Pong pongCount = pongCount + 1 case Stop => Console . println ( &quot;Pong: stop&quot; ) exit () val pong = new Pong val ping = new Ping ( 100000 , pong ) ping . start pong . start With the advent of multi-core processors concurrent programming is becoming indispensable. Actors are basically concurrent processes that communicate by exchanging messages, instead of sharing state.
  • 40. Companion objects and Static Singleton and Static considered harmful Static methods cannot be polymorphic Inheritance problems So - all static members are now grouped in their own ‘object’ Scala’s “companion ‘object’” (singleton object)
  • 41. More and more and more…. Nested Functions By-name parameters Lazy evaluation Logging – no more stupid ( if ( log.isEnabled() ) protection! ) Private packages LiftWeb (Rails/Grails like web app for Scala) The Option type – optional values – Some or None First-class Properties coming… Properties are objects (OO sense) Govern access to a (possibly calculated) field. Properties can have other methods in addition to get/set logic, such as registering event listeners. Writing new control structures val file = new File ( &quot;date.txt&quot; ) withPrintWriter ( file ) { writer => writer.println ( new java.util.Date ) }
  • 42. More Technologies are out there! Expand your mind! Online Ajax HelpRequestList program in 9 lines!! Groovy on Grails Maven the modular build system Connoisseur! Groovy Builder and G-Strings Groovy Command Line Interpreter Groovy Wicket builder Polygot programming a computer program or script written in a valid form of multiple programming languages , which performs the same operations or output independently of the programming language used to compile or interpret it. Git a distributed revision control / software configuration management project created by Linus Torvalds , initially for the Linux kernel development.
  • 43. The Full Article Read the article at: http://stubbisms.wordpress.com/2008/02/22/my-foray-into-the-world-of-scala/ More Scala links scala-lang.org Thanks for listening!