Introducing Scala By Prasanna Kumar JUG-C group meetup  11 June 2011
About me Java programmer turned Scala “enthusiast” Started (learning) with scala very recently :-) Explored almost all the workaround to setup development environment for Scala Committer of Kandash project - Kanban dashboard application http://code.google.com/p/kandash/ Reach me  Email :  [email_address] Twitter : @prassee Blog :http://prassee.tumblr.com/
Topic Covered What is Scala? Why Scala? Basics of Scala Scala development environment  (a small demo with Intellij IDEA & SBT) Scala Frameworks Learning Resources Recent News / updates Questions ?
What is Scala
Brief History A JVM language  Source code compiled in to .class file which can be deployed in to any JVM / Container Blend of OOP and Functional OP Invented by Martin Odersky & Team Key developer behind Generics in Java Created functional language called pizza Under the incubation of EPFL  (École Polytechnique Fédérale de Lausanne) ???
Motivations Considered as the Java of the Feature !!!!!!!!!  Has many good features already which are much awaited or still under development in Java 7 , 8 ... etc Increasingly becoming popular language
Who is using
Why Scala ? Comparatively less code (Less chance of introducing defects) Modular code – (coz of imperative & functional model) Maintainable code (easy to extend) Less side effects (by following functional & less state agonistic code) Seamless integration with Java  Existing java code can be used in Scala – vice versa
Basics of Scala
Hello World – first Scala program !!! object  HelloWorld {   def  main(args: Array[String]) {   println("Hello World") } } object  HelloWorld  e xtends  Application { // no need of main method  println("Hello World") } Output:  Hello World
Programming Constructs
Variables Scala has two types of variables var & val Var – read write Val – read only Type inference  val i=23 // inferred to int val str = “string” // inferred to int scala> val array: Array[String] = new Array(5) array: Array[String] = Array(null, null, null, null, null) scala> array = new Array(2)  <console>:5: error: reassignment to val array = new Array(2)
Conditional Statements If statement follows the same syntax as with java , however if statements are expressions by themselves // normal usage if(1>2) { println(&quot;1 is greater&quot;) } else { println(&quot;2 is greater&quot;) } // usage of if stmt as expressions val xpr = if(1>2) { 1 } else { 2 } println(&quot;result of if expr is &quot;+xpr)
Loops For loops  Much comprehended than java -> more flexibility  and functional agonistic def forTest() { val list = List(1,2,3,4) for(valus<- list) { print(valus)  // prints 1 2 3 4 } // prints 1 2 3 4 list.foreach(print(_)) // conditional if stmts inside for for(numbs <- list if(numbs > 2)) { println(&quot;numbers greater than 2 &quot; +numbs) } // multiple if stmts inside for for(nums <- list if(nums >1); if(nums<4)) { println(&quot;Filtered numbers&quot; + nums) } }
While and do-While While loop also share the same syntax of java (or any other imperative language) // while stmt var a =0 while(a<10) { a =a +1 println(a) } // do while stmt var count = 0 do { count += 1 println(count) } while (count < 10)
First Class in Scala The first scala class // class declaration with default constructor class Rational(n:Int,d:Int) {  val num = n // public by default  val den = d /* auxillary constructor definitions */ def this(n:Int) = this(n,1) // auxiallry constructor  /* method definitions */ def +(that:Rational):Rational = new Rational(num*that.den + den*that.num ,den*that.den) def +(i:Int):Rational = new Rational(num * i,den) // override key word is mandatory while overridding methods override def toString = num + &quot;/&quot; + den }
Named & Default Parameters Parameters can be given default values  class Rational(n:Int,d:Int = 1) { ...... ...... } Rational(2) // use of default param Rational(d=4,n=7) // order of param has changed still no impact due to named param Avoid creating overloaded method (but only when necessary)
Case classes Scala's approach of pattern matching  very flexible  Elegant syntax  No need to create objects  Classes prefixed with 'case' keyword case class Java(vers:String) { override def version: String = &quot;1.6&quot; // no need of braces for single line } // usage  case class Scala(vers:String) { override def version: String = &quot;2.9.0&quot; // no need of braces for single line } for (languages <- list) { languages match { case Java(&quot;1.6&quot;) => { println(languages.version) } case Scala(&quot;2.9&quot;) => { println(languages.version) } } }
Companion classes Scala's approach to static methods  Unlike Java Scala doesn't have static keyword  Classes can be created with the keyword 'object' methods inside such classes can be accessed without creating objects object Printer { def print(file:File) { println(&quot;printing file&quot;) } } Companion classes are those which shares the name of the originating class and has to exist in the same source file Can be useful for creating factory classes
Traits Scala's approach to Interfaces (as in Java) Unlike Java, Scala's  traits can have implementation Like final keyword in java Scala provides a key word called 'sealed' to define classes and traits to prevent inheritance. - sealed class StringUtils { … ....  } trait IntSet {  def contains(x: Int): Boolean def notContains(x: A) = !contains(x)  def add(x: Int): IntSet } object EmptySet extends IntSet {  def contains(x: Int): Boolean = false  def add(x: Int): IntSet = new NonEmptySet(x, EmptySet, EmptySet) } class NonEmptySet(elem: Int, left: IntSet, right: IntSet) extends IntSet {  def contains(x: Int): Boolean = if (x < elem) left contains x else if (x > elem) right contains x else true def add(x: Int): IntSet = if (x < elem) new NonEmptySet(elem, left add x, right) else if (x > elem) new NonEmptySet(elem, left, right add x) else this }
Packages // unlike java import stmts are relative to java // and independent of physical location package org { package jugc { import scalatweet.Tweeter  // imports are relative class TweeterClient { val tweeter = new Tweeter(); tweeter.findAllMyTweets(&quot;prassee&quot;) } package scala { class ComClass1 { def whereIam = &quot;org.jugc.scala.ComClass1&quot; }}}} package org.jugc.scala { class ComClass2 { def whereIam = &quot;org.jugc.scala.ComClass2&quot; } } package org.jugc.scalatweet { class Tweeter { def findAllMyTweets(userId: String): List[String] = List(&quot;gave a presentation on scala&quot;, &quot;blogged about scala&quot;) } }
Exception Handling package org.jugc.scalatweet { import java.io.{FileNotFoundException, FileReader} class Tweeter { def findAllMyTweets(userId: String): List[String] = List(&quot;gave a presentation on scala&quot;, &quot;blogged about scala&quot;) def post(tweet:String) { } def postTweet() { try { val f = new FileReader(&quot;input.txt&quot;) f.read() } catch { case ex:FileNotFoundException => { throw new TweetPostException() } case ex:Exception => // handle exception thwow } } } class TweetPostException extends Exception { } }
Scala's Type Heirachy
Setting up development environment  Scala has plugins for  Eclipse  Netbeans Intellij IDEA  All the above have SBT integration (good news) !!!  Case Study  Intellij IDEA  Community edition (still a good IDE for kick starting with Scala development)  (Not promoting IDEA in anyway) Over to demo session !!!!  Or refer to my latest blog post http://prassee.tumblr.com/post/6338223573/scalaide  -  Eclipse looks promising !!!!!!  My suggestion is to consider all the above 3 IDE's for development
Frameworks There are lot of frameworks for Scala (like java) Scala test – Unit testing  Specs -  BDD  Akka - concurrency Junit integration (seamless) Lift for web 2.0 Scalatra – templating engine .......  A lot more !!!!!!!
Learning Resources Books  The most prominent books for learning scala  - from the source More books to come ......
Learning Resources Blogs  http://www.scala-lang.org/node/104 http://www.scala-blogs.org/2007/12/scala-statically-typed-dynamic-language.html http://www.scala-lang.org/node/8610 Create a blog for yourself  Tweet about it !!!  JUG-C google groups !!!  Effective use of Stack Overflow Ask questions  Answering questions  Quuick response  Professional community  Open to opinions
Learning levels Have levels for your self while learning the language this really helps !!!!  Level A1: Beginning application programmer Java-like statements and expressions: standard operators, method calls, conditionals, loops, try/catch class, object, def, val, var, import, package Infix notation for method calls Simple closures Collections with map, filter, etc for-expressions Level A2: Intermediate application programmer Pattern matching Trait composition Recursion, in particular tail recursion XML literals Level A3: Expert application programmer Folds, i.e. methods such as foldLeft, foldRight Streams and other lazy data structures Actors Combinator parsers Level L1: Junior library designer Type parameters Traits Lazy vals Control abstraction, currying By-name parameters Level L2: Senior library designer Variance annotations Existential types (e.g., to interface with Java wildcards) Self type annotations and the cake pattern for dependency injection Structural types (aka static duck typing) Defining map/flatmap/withFilter for new kinds of for-expressions Extractors Level L3: Expert library designer Early initializers Abstract types Implicit definitions Higher-kinded types
Recent News updates Typesafe  A company formed by Martin odersky and Jonas boner (Akka) Launched a Typesafe stack A scala development stack – opensource !!! James Gosling !!! - inventor of java honoured with the post of member of advisory board Lot of updates coming on  Cloud foundry  Launched by VMWare  Announed a PaaS service  Included support for Scala  http://blog.cloudfoundry.com/post/6109591023/cloud-foundry-now-supporting-scala JUG-C Initiatives Scalatweet a lift based web app under development @scalatweet Open for community participation
Questions ?
Thank you !!!!!

Scala presentationjune112011

  • 1.
    Introducing Scala ByPrasanna Kumar JUG-C group meetup 11 June 2011
  • 2.
    About me Javaprogrammer turned Scala “enthusiast” Started (learning) with scala very recently :-) Explored almost all the workaround to setup development environment for Scala Committer of Kandash project - Kanban dashboard application http://code.google.com/p/kandash/ Reach me Email : [email_address] Twitter : @prassee Blog :http://prassee.tumblr.com/
  • 3.
    Topic Covered Whatis Scala? Why Scala? Basics of Scala Scala development environment (a small demo with Intellij IDEA & SBT) Scala Frameworks Learning Resources Recent News / updates Questions ?
  • 4.
  • 5.
    Brief History AJVM language Source code compiled in to .class file which can be deployed in to any JVM / Container Blend of OOP and Functional OP Invented by Martin Odersky & Team Key developer behind Generics in Java Created functional language called pizza Under the incubation of EPFL (École Polytechnique Fédérale de Lausanne) ???
  • 6.
    Motivations Considered asthe Java of the Feature !!!!!!!!! Has many good features already which are much awaited or still under development in Java 7 , 8 ... etc Increasingly becoming popular language
  • 7.
  • 8.
    Why Scala ?Comparatively less code (Less chance of introducing defects) Modular code – (coz of imperative & functional model) Maintainable code (easy to extend) Less side effects (by following functional & less state agonistic code) Seamless integration with Java Existing java code can be used in Scala – vice versa
  • 9.
  • 10.
    Hello World –first Scala program !!! object HelloWorld { def main(args: Array[String]) { println(&quot;Hello World&quot;) } } object HelloWorld e xtends Application { // no need of main method println(&quot;Hello World&quot;) } Output: Hello World
  • 11.
  • 12.
    Variables Scala hastwo types of variables var & val Var – read write Val – read only Type inference val i=23 // inferred to int val str = “string” // inferred to int scala> val array: Array[String] = new Array(5) array: Array[String] = Array(null, null, null, null, null) scala> array = new Array(2) <console>:5: error: reassignment to val array = new Array(2)
  • 13.
    Conditional Statements Ifstatement follows the same syntax as with java , however if statements are expressions by themselves // normal usage if(1>2) { println(&quot;1 is greater&quot;) } else { println(&quot;2 is greater&quot;) } // usage of if stmt as expressions val xpr = if(1>2) { 1 } else { 2 } println(&quot;result of if expr is &quot;+xpr)
  • 14.
    Loops For loops Much comprehended than java -> more flexibility and functional agonistic def forTest() { val list = List(1,2,3,4) for(valus<- list) { print(valus) // prints 1 2 3 4 } // prints 1 2 3 4 list.foreach(print(_)) // conditional if stmts inside for for(numbs <- list if(numbs > 2)) { println(&quot;numbers greater than 2 &quot; +numbs) } // multiple if stmts inside for for(nums <- list if(nums >1); if(nums<4)) { println(&quot;Filtered numbers&quot; + nums) } }
  • 15.
    While and do-WhileWhile loop also share the same syntax of java (or any other imperative language) // while stmt var a =0 while(a<10) { a =a +1 println(a) } // do while stmt var count = 0 do { count += 1 println(count) } while (count < 10)
  • 16.
    First Class inScala The first scala class // class declaration with default constructor class Rational(n:Int,d:Int) { val num = n // public by default val den = d /* auxillary constructor definitions */ def this(n:Int) = this(n,1) // auxiallry constructor /* method definitions */ def +(that:Rational):Rational = new Rational(num*that.den + den*that.num ,den*that.den) def +(i:Int):Rational = new Rational(num * i,den) // override key word is mandatory while overridding methods override def toString = num + &quot;/&quot; + den }
  • 17.
    Named & DefaultParameters Parameters can be given default values class Rational(n:Int,d:Int = 1) { ...... ...... } Rational(2) // use of default param Rational(d=4,n=7) // order of param has changed still no impact due to named param Avoid creating overloaded method (but only when necessary)
  • 18.
    Case classes Scala'sapproach of pattern matching very flexible Elegant syntax No need to create objects Classes prefixed with 'case' keyword case class Java(vers:String) { override def version: String = &quot;1.6&quot; // no need of braces for single line } // usage case class Scala(vers:String) { override def version: String = &quot;2.9.0&quot; // no need of braces for single line } for (languages <- list) { languages match { case Java(&quot;1.6&quot;) => { println(languages.version) } case Scala(&quot;2.9&quot;) => { println(languages.version) } } }
  • 19.
    Companion classes Scala'sapproach to static methods Unlike Java Scala doesn't have static keyword Classes can be created with the keyword 'object' methods inside such classes can be accessed without creating objects object Printer { def print(file:File) { println(&quot;printing file&quot;) } } Companion classes are those which shares the name of the originating class and has to exist in the same source file Can be useful for creating factory classes
  • 20.
    Traits Scala's approachto Interfaces (as in Java) Unlike Java, Scala's traits can have implementation Like final keyword in java Scala provides a key word called 'sealed' to define classes and traits to prevent inheritance. - sealed class StringUtils { … .... } trait IntSet { def contains(x: Int): Boolean def notContains(x: A) = !contains(x) def add(x: Int): IntSet } object EmptySet extends IntSet { def contains(x: Int): Boolean = false def add(x: Int): IntSet = new NonEmptySet(x, EmptySet, EmptySet) } class NonEmptySet(elem: Int, left: IntSet, right: IntSet) extends IntSet { def contains(x: Int): Boolean = if (x < elem) left contains x else if (x > elem) right contains x else true def add(x: Int): IntSet = if (x < elem) new NonEmptySet(elem, left add x, right) else if (x > elem) new NonEmptySet(elem, left, right add x) else this }
  • 21.
    Packages // unlikejava import stmts are relative to java // and independent of physical location package org { package jugc { import scalatweet.Tweeter // imports are relative class TweeterClient { val tweeter = new Tweeter(); tweeter.findAllMyTweets(&quot;prassee&quot;) } package scala { class ComClass1 { def whereIam = &quot;org.jugc.scala.ComClass1&quot; }}}} package org.jugc.scala { class ComClass2 { def whereIam = &quot;org.jugc.scala.ComClass2&quot; } } package org.jugc.scalatweet { class Tweeter { def findAllMyTweets(userId: String): List[String] = List(&quot;gave a presentation on scala&quot;, &quot;blogged about scala&quot;) } }
  • 22.
    Exception Handling packageorg.jugc.scalatweet { import java.io.{FileNotFoundException, FileReader} class Tweeter { def findAllMyTweets(userId: String): List[String] = List(&quot;gave a presentation on scala&quot;, &quot;blogged about scala&quot;) def post(tweet:String) { } def postTweet() { try { val f = new FileReader(&quot;input.txt&quot;) f.read() } catch { case ex:FileNotFoundException => { throw new TweetPostException() } case ex:Exception => // handle exception thwow } } } class TweetPostException extends Exception { } }
  • 23.
  • 24.
    Setting up developmentenvironment Scala has plugins for Eclipse Netbeans Intellij IDEA All the above have SBT integration (good news) !!! Case Study Intellij IDEA Community edition (still a good IDE for kick starting with Scala development) (Not promoting IDEA in anyway) Over to demo session !!!! Or refer to my latest blog post http://prassee.tumblr.com/post/6338223573/scalaide - Eclipse looks promising !!!!!! My suggestion is to consider all the above 3 IDE's for development
  • 25.
    Frameworks There arelot of frameworks for Scala (like java) Scala test – Unit testing Specs - BDD Akka - concurrency Junit integration (seamless) Lift for web 2.0 Scalatra – templating engine ....... A lot more !!!!!!!
  • 26.
    Learning Resources Books The most prominent books for learning scala - from the source More books to come ......
  • 27.
    Learning Resources Blogs http://www.scala-lang.org/node/104 http://www.scala-blogs.org/2007/12/scala-statically-typed-dynamic-language.html http://www.scala-lang.org/node/8610 Create a blog for yourself Tweet about it !!! JUG-C google groups !!! Effective use of Stack Overflow Ask questions Answering questions Quuick response Professional community Open to opinions
  • 28.
    Learning levels Havelevels for your self while learning the language this really helps !!!! Level A1: Beginning application programmer Java-like statements and expressions: standard operators, method calls, conditionals, loops, try/catch class, object, def, val, var, import, package Infix notation for method calls Simple closures Collections with map, filter, etc for-expressions Level A2: Intermediate application programmer Pattern matching Trait composition Recursion, in particular tail recursion XML literals Level A3: Expert application programmer Folds, i.e. methods such as foldLeft, foldRight Streams and other lazy data structures Actors Combinator parsers Level L1: Junior library designer Type parameters Traits Lazy vals Control abstraction, currying By-name parameters Level L2: Senior library designer Variance annotations Existential types (e.g., to interface with Java wildcards) Self type annotations and the cake pattern for dependency injection Structural types (aka static duck typing) Defining map/flatmap/withFilter for new kinds of for-expressions Extractors Level L3: Expert library designer Early initializers Abstract types Implicit definitions Higher-kinded types
  • 29.
    Recent News updatesTypesafe A company formed by Martin odersky and Jonas boner (Akka) Launched a Typesafe stack A scala development stack – opensource !!! James Gosling !!! - inventor of java honoured with the post of member of advisory board Lot of updates coming on Cloud foundry Launched by VMWare Announed a PaaS service Included support for Scala http://blog.cloudfoundry.com/post/6109591023/cloud-foundry-now-supporting-scala JUG-C Initiatives Scalatweet a lift based web app under development @scalatweet Open for community participation
  • 30.
  • 31.