SlideShare a Scribd company logo
1 of 58
Download to read offline
Scala for Java Developers
    Michael Galpin, http://fupeg.blogspot.com




Tuesday, January 13, 2009
Scala is...

         A general purpose programming language
    ✤




         A language that runs on the Java VM
    ✤




               Statically typed
          ✤




         An object-oriented language
    ✤




               No primitives or operators, but with singletons
          ✤




         A functional language
    ✤




         A scalable language
    ✤



Tuesday, January 13, 2009
Scala is General Purpose


         Some uses of Scala
    ✤




               Scripting
          ✤




               Web applications
          ✤




               Messaging
          ✤




               Graphical User Interfaces
          ✤




Tuesday, January 13, 2009
Scala runs on the JVM


         Compiles to Java bytecode
    ✤




               Written by Martin Odersky (javac)
          ✤




         Uses core Java heavily
    ✤




         Can call any Java classes
    ✤




         Can be called by any Java class
    ✤




Tuesday, January 13, 2009
Scala is Statically Typed

                            var name :String = quot;Hello, worldquot; ;




Tuesday, January 13, 2009
Scala is Statically Typed

                            var name = quot;Hello, worldquot; ;




Tuesday, January 13, 2009
Scala is Statically Typed

                            var name = quot;Hello, worldquot;




Tuesday, January 13, 2009
Scala is Statically Typed

                            val name = quot;Hello, worldquot;




Tuesday, January 13, 2009
Scala is Statically Typed

                                  val name = quot;Hello, worldquot;




                            def makeList(a:String, b:String):List[String] = {

                                return   a :: b :: Nil ;

                            }




Tuesday, January 13, 2009
Scala is Statically Typed

                                  val name = quot;Hello, worldquot;




                            def makeList(a:String, b:String):List[String] = {

                                return   a :: b :: Nil

                            }




Tuesday, January 13, 2009
Scala is Statically Typed

                                   val name = quot;Hello, worldquot;




                            def makeList(a:String, b:String):List[String] = {

                                a :: b :: Nil

                            }




Tuesday, January 13, 2009
Scala is Statically Typed

                                  val name = quot;Hello, worldquot;




                            def makeList(a:String, b:String):List[String] = a :: b :: Nil




Tuesday, January 13, 2009
Scala is Statically Typed

                                  val name = quot;Hello, worldquot;




                            def makeList(a:String, b:String)   = a :: b :: Nil




Tuesday, January 13, 2009
Scala is object-oriented


         Classes
    ✤



         class Computer (val clockSpeed:Double, var memory:Int, var hdd:Int, var os:String){
             def this(clockSpeed:Double) = this(clockSpeed, 0, 0, null)
             def addMemory(newRam:Int):Unit = {
                 this.memory += newRam
             }
             def addDrive(newHdd:Int) = {
                 this.hdd += newHdd
             }
             override def toString = clockSpeed + quot; GHz quot; + memory + quot; GB RAM quot; + hdd + quot; GB hdd quot; + os
         }




Tuesday, January 13, 2009
Scala is object-oriented

         Inheritance
    ✤
         class Laptop(clockSpeed:Double, memory:Int, hdd:Int, val screenSize:Int, os:String) extends
         Computer(clockSpeed,memory,hdd,os){
             override def toString = screenSize + quot; inch screen quot; + super.toString
         }



         Mix-ins
    ✤
         trait Mac{
             var osVersion:String
             def osx = {
                 osVersion match {
                     case quot;10.5quot; => quot;Leopardquot;
                     case quot;10.4quot; => quot;Tigerquot;
                     case _ => quot;OSXquot;
                 }
             }
         }

         class MacBook(clockSpeed:Double, memory:Int, hdd:Int, os:String) extends Laptop(clockSpeed,
         memory, hdd, 13, os) with Mac{
             var osVersion = os
         }


Tuesday, January 13, 2009
Scala has More Effective Java




Tuesday, January 13, 2009
Scala has More Effective Java


         You always override equals, hashCode, and toString ... right?
    ✤




Tuesday, January 13, 2009
Scala has More Effective Java


         You always override equals, hashCode, and toString ... right?
    ✤




         Case Classes
    ✤
         case class Player(val name:String, val team:String, val position:String)
         val tebow = Player(quot;Tim Tebowquot;,quot;Floridaquot;,quot;QBquot;)
         println(tebow) // prints (Time Tebow,Florida,QB)

         val clone = Player(quot;Tim Tebowquot;,quot;Floridaquot;,quot;QBquot;)
         println(clone == tebow) // prints true

         val set = new HashSet[Player]
         set += tebow
         set += clone

         println(set.size) // prints 1




Tuesday, January 13, 2009
Scala is very object-oriented

         No primitives
    ✤




               No int, just Int
          ✤




               No String[], just Array[String]
          ✤




         No operators
    ✤




               + - * / ++ += are all just methods
          ✤




               Create your own or overload (if not final)
          ✤




Tuesday, January 13, 2009
No Operators, Just Methods




Tuesday, January 13, 2009
No Operators, Just Methods



         Dots and parentheses are optional
    ✤
         val x = 1.+(2)
         val y = 1 + 2
         println(x == y) // prints true




Tuesday, January 13, 2009
No Operators, Just Methods



         Dots and parentheses are optional
    ✤
         val x = 1.+(2)
         val y = 1 + 2
         println(x == y) // prints true



         Sweet Syntactic Sugar
    ✤
         val cache = new HashMap[String, String]
         cache += (quot;fooquot;,quot;barquot;)
         cache -= quot;fooquot;




Tuesday, January 13, 2009
Great for DSLs



         Domain Specific Languages
    ✤




               XML
          ✤




               Actors
          ✤




Tuesday, January 13, 2009
XML Example: Atom


 class Entry(var title:String, val link:String, val id:String, var updated:Date, var summary:String){
     def toAtom =
     <entry>
         <link href={link}/>
         <id>{id}</id>
         <updated>{updated}</updated>
         <summary>{summary}</summary>
     </entry>
 }




Tuesday, January 13, 2009
XML Example: Atom
 class Feed(val title:String, val link:String, var updated:Date, val author:String, val id:String){
     var entries:List[Entry] = Nil

       def addEntry(entry:Entry){
           entries = entry :: entries
       }

       def toAtom =
       <feed>
           <title>{title}</title>
           <link href={link}/>
           <updated>{updated}</updated>
           <author>
               <name>{author}</name>
           </author>
           <id>{id}</id>
           {
               val nodes = new NodeBuffer
               for (entry <- entries) {
                    nodes &+ entry.toAtom
               }
               nodes
           }
       </feed>
 }
Tuesday, January 13, 2009
XML Example: Atom


              object Atom{
                  def main(args:Array[String]){
                      val f = new Feed(quot;Programming and Politicsquot;, quot;http://fupeg.blogspot.comquot;,
                           new Date(),quot;Michel Galpinquot;,quot;5819005quot;)
                      val e = new Entry(quot;New Scala Articlequot;,
                          quot;http://fupeg.blogspot.com/2008/04/new-scala-article.htmlquot;,
                          quot;6009113042595594848quot;, new Date(), quot;Article on Scala and XMLquot; )
                      f.addEntry(e)
                      println(f.toAtom)
                  }
              }




Tuesday, January 13, 2009
XML Example: Atom

        $ scalac Atom.scala
        $ scala Atom
        <feed>
               <title>Programming and Politics</title>
               <link href=quot;http://fupeg.blogspot.comquot;></link>
               <updated>Tue Jan 13 11:35:51 PST 2009</updated>
               <author>
                  <name>Michel Galpin</name>
               </author>
               <id>5819005</id>
               <entry>
               <link href=quot;http://fupeg.blogspot.com/2008/04/new-scala-article.htmlquot;></link>
               <id>6009113042595594848</id>
               <updated>Tue Jan 13 11:35:51 PST 2009</updated>
               <summary>Scala is good</summary>
           </entry>
           </feed>




Tuesday, January 13, 2009
Singletons in Scala


         Use object instead of class
    ✤
         object ComputerStore{
             def main(args:Array[String]) = {
                 val newton = new MacBook(2.0, 2048, 120, quot;10.5quot;)
                 println(newton.clockSpeed + quot; is fast!quot;)
                 println(quot;newton is running quot; + newton.osx)
             }
         }



         Often used as factories a.k.a. companion objects
    ✤
         val names = List(quot;Billquot;, quot;Davidquot;, quot;Michaelquot;)




Tuesday, January 13, 2009
Scala is functional


         A function is an object, its definition is its apply method
    ✤
         object DotProdct{
             def apply(list1:List[Number], list2:[Number]) = {
                 var result = 0
                 for (i <- 0 until list1.size){
                     result += list1(i)*list2(i)
                 }
                 result
             }
         }
         val a = List(1,2,3)
         val b = List(4,5,6)
         println(DotProduct(a,b)) // prints 32




Tuesday, January 13, 2009
Closures


         Functions can be passed as parameters to other functions
    ✤




         Scala allows for inline (anonymous) functions
    ✤




               Still statically typed
          ✤




               Lexically scoped (anonymous or not)
          ✤




Tuesday, January 13, 2009
Closure Examples




Tuesday, January 13, 2009
Closure Examples
                  class Person(val firstName:String, val middleName:String, var lastName:String){
                      def print( formatter:(String,String,String) => String )={
                          val str = formatter(firstName,middleName,lastName)
                          println(str)
                      }
                  }




Tuesday, January 13, 2009
Closure Examples
                  class Person(val firstName:String, val middleName:String, var lastName:String){
                      def print( formatter:(String,String,String) => String )={
                          val str = formatter(firstName,middleName,lastName)
                          println(str)
                      }
                  }
                   val p = new Person(quot;Michaelquot;,quot;Davidquot;,quot;Galpinquot;)




Tuesday, January 13, 2009
Closure Examples
                  class Person(val firstName:String, val middleName:String, var lastName:String){
                      def print( formatter:(String,String,String) => String )={
                          val str = formatter(firstName,middleName,lastName)
                          println(str)
                      }
                  }
                   val p = new Person(quot;Michaelquot;,quot;Davidquot;,quot;Galpinquot;)

                  val sep = quot; quot;
                  def std(a:String,b:String,c:String) = List(a,b,c).mkString(sep)
                  p.print(std)




Tuesday, January 13, 2009
Closure Examples
                  class Person(val firstName:String, val middleName:String, var lastName:String){
                      def print( formatter:(String,String,String) => String )={
                          val str = formatter(firstName,middleName,lastName)
                          println(str)
                      }
                  }
                   val p = new Person(quot;Michaelquot;,quot;Davidquot;,quot;Galpinquot;)

                  val sep = quot; quot;
                  def std(a:String,b:String,c:String) = List(a,b,c).mkString(sep)
                  p.print(std)

                  val sep2 = quot;:quot;
                  p.print( (a,b,c) => a + sep + b + sep2 + c)




Tuesday, January 13, 2009
Closure Examples
                  class Person(val firstName:String, val middleName:String, var lastName:String){
                      def print( formatter:(String,String,String) => String )={
                          val str = formatter(firstName,middleName,lastName)
                          println(str)
                      }
                  }
                   val p = new Person(quot;Michaelquot;,quot;Davidquot;,quot;Galpinquot;)

                  val sep = quot; quot;
                  def std(a:String,b:String,c:String) = List(a,b,c).mkString(sep)
                  p.print(std)

                  val sep2 = quot;:quot;
                  p.print( (a,b,c) => a + sep + b + sep2 + c)


                  p.print(_ + sep + _ + sep2 + _)




Tuesday, January 13, 2009
Closures: Not Just for Golf




Tuesday, January 13, 2009
Closures: Not Just for Golf
                            var nums = 1 until 100 filter(_ % 3 == 0)




Tuesday, January 13, 2009
Closures: Not Just for Golf
                            var nums = 1 until 100 filter(_ % 3 == 0)

                            nums.foreach(println(_))




Tuesday, January 13, 2009
Closures: Not Just for Golf
                            var nums = 1 until 100 filter(_ % 3 == 0)

                            nums.foreach(println(_))

                            nums = nums.map(2*_ + 3)
                            println(quot;All greater than 10? quot; + nums.forall(_ > 10))




Tuesday, January 13, 2009
Closures: Not Just for Golf
                            var nums = 1 until 100 filter(_ % 3 == 0)

                            nums.foreach(println(_))

                            nums = nums.map(2*_ + 3)
                            println(quot;All greater than 10? quot; + nums.forall(_ > 10))

                            val sum = nums.foldLeft(0)(_+_)
                            println(quot;sum=quot;+sum)




Tuesday, January 13, 2009
Closures: Not Just for Golf
                            var nums = 1 until 100 filter(_ % 3 == 0)

                            nums.foreach(println(_))

                            nums = nums.map(2*_ + 3)
                            println(quot;All greater than 10? quot; + nums.forall(_ > 10))

                            val sum = nums.foldLeft(0)(_+_)
                            println(quot;sum=quot;+sum)

                            val sorted = nums.toList.sort( (n,m) => {
                                val remN = n % 5
                                val remM = m % 5
                                remN > remM
                            })
                            sorted.foreach( (i) => println(i + quot; quot; + i % 5))




Tuesday, January 13, 2009
Scala: A Scalable Language


         Compiles to bytecode
    ✤




               Very close to “native” Java
          ✤




         Sometimes faster!
    ✤




               Tail recursion
          ✤




               Concurrency
          ✤




Tuesday, January 13, 2009
Scala: Better Bytecode

                 What is the first triangle number to have at least N divisors?
                            Time




                                              N


Tuesday, January 13, 2009
Tail Recursion: Scala Factorial

                            object Factorial{
                                val ZERO = BigInt.int2bigInt(0)
                                val ONE = BigInt.int2bigInt(1)
                                def factorial(n:BigInt):BigInt= n match {
                                    case ZERO => ONE
                                    case ONE => ONE
                                    case _ => n*factorial(n-1)
                                }
                                def main(args:Array[String]){
                                    val i = args(0).toInt
                                    val n = BigInt.int2bigInt(i)
                                    val start = new java.util.Date
                                    println(factorial(n))
                                    val duration = (new java.util.Date()).getTime - start.getTime
                                    println(quot;duration=quot;+duration)
                                }
                            }




Tuesday, January 13, 2009
And in Java...
                            import java.math.BigInteger;
                            import java.util.Date;

                            public class Factorial{
                                public static BigInteger factorial(BigInteger n){
                                    if (n.equals(BigInteger.ZERO))
                                         return BigInteger.ONE;
                                    else if (n.equals(BigInteger.ONE))
                                         return BigInteger.ONE;
                                    else
                                         return n.multiply(factorial(n.subtract(BigInteger.ONE)));
                                }

                                public static void main(String[] args){
                                    BigInteger n = new BigInteger(args[0]);
                                    Date start = new Date();
                                    System.out.println(factorial(n));
                                    long duration = (new Date()).getTime() - start.getTime();
                                    System.out.println(quot;duration=quot;+duration);
                                }
                            }



Tuesday, January 13, 2009
And the Results...
                                                   Factorial
                       100000




                       75000
            Time(ms)




                       50000




                       25000




                           0
                            10000   20000                      30000    50000
                                                      N




                                            Java                Scala




Tuesday, January 13, 2009
Scala Concurrency: Actors




Tuesday, January 13, 2009
Scala Concurrency: Actors


         Actor Model: A Different Way to Implement Concurrency
    ✤




Tuesday, January 13, 2009
Scala Concurrency: Actors


         Actor Model: A Different Way to Implement Concurrency
    ✤




               Each Object is an Actor
          ✤




Tuesday, January 13, 2009
Scala Concurrency: Actors


         Actor Model: A Different Way to Implement Concurrency
    ✤




               Each Object is an Actor
          ✤




               Each Actor has a Mailbox
          ✤




Tuesday, January 13, 2009
Scala Concurrency: Actors


         Actor Model: A Different Way to Implement Concurrency
    ✤




               Each Object is an Actor
          ✤




               Each Actor has a Mailbox
          ✤




               Actors (Asynchronously) Send Messages and Receive them in their
          ✤

               Mailbox




Tuesday, January 13, 2009
Scala Concurrency: Actors


         Actor Model: A Different Way to Implement Concurrency
    ✤




               Each Object is an Actor
          ✤




               Each Actor has a Mailbox
          ✤




               Actors (Asynchronously) Send Messages and Receive them in their
          ✤

               Mailbox

               No Shared State
          ✤




Tuesday, January 13, 2009
Why Actors: Performance
                                                Apache (C/Threads) vs. Yaws (Erlang/Actors)
                            Throughput (KB/s)




                                                             Concurrent Sessions
Tuesday, January 13, 2009
Why Actors: Simpler Code



         No Code Changes for Multi-threaded vs. Single-threaded
    ✤




         No Mutable State
    ✤




         No (Dead) Locking
    ✤




Tuesday, January 13, 2009
Actor Example
     case object Ping
     case object Pong
     case object Stop

     class Pong extends Actor {
         def act() {
             var pongCount = 0
             loop {
                 react {
                     case Ping =>
                         if (pongCount % 1000 == 0) // print every 1000th Ping
                         println(quot;Pong: ping quot;+pongCount)
                         sender ! Pong
                         pongCount = pongCount + 1
                     case Stop =>
                         println(quot;Pong: stopquot;)
                         exit()
                 }
             }
         }
     }




Tuesday, January 13, 2009
Actor Example
     class Ping(count: Int, pong: Actor) extends Actor {
         def act(){
             var pingsLeft = count - 1
             pong ! Ping
             loop{
                 react {
                     case Pong =>
                         if (pingsLeft % 1000 == 0) // print every 1000th Pong
                             println(quot;Ping: pongquot;)
                         if (pingsLeft > 0){
                             pong ! Ping
                             pingsLeft -= 1
                         } else {
                             println(quot;Ping: stopquot;)
                             pong ! Stop
                             exit()
                         }
                 }
             }
         }
     }




Tuesday, January 13, 2009
Actor Example
     object PingPong {
         def main(args:Array[String]){
           val pong = new Pong
           val ping = new Ping(100000, pong)
           ping.start
           pong.start
         }
     }




Tuesday, January 13, 2009

More Related Content

What's hot

Scala : language of the future
Scala : language of the futureScala : language of the future
Scala : language of the futureAnsviaLab
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesTomer Gabel
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Developmentvito jeng
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghStuart Roebuck
 
Ankara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with ScalaAnkara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with ScalaEnsar Basri Kahveci
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from javaIndicThreads
 
Practically Functional
Practically FunctionalPractically Functional
Practically Functionaldjspiewak
 
Functional Algebra: Monoids Applied
Functional Algebra: Monoids AppliedFunctional Algebra: Monoids Applied
Functional Algebra: Monoids AppliedSusan Potter
 
Java Keeps Throttling Up!
Java Keeps Throttling Up!Java Keeps Throttling Up!
Java Keeps Throttling Up!José Paumard
 
The Evolution of Scala / Scala進化論
The Evolution of Scala / Scala進化論The Evolution of Scala / Scala進化論
The Evolution of Scala / Scala進化論scalaconfjp
 
scala.reflect, Eugene Burmako
scala.reflect, Eugene Burmakoscala.reflect, Eugene Burmako
scala.reflect, Eugene BurmakoVasil Remeniuk
 
A Scala Corrections Library
A Scala Corrections LibraryA Scala Corrections Library
A Scala Corrections LibraryPaul Phillips
 

What's hot (20)

Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
 
Scala : language of the future
Scala : language of the futureScala : language of the future
Scala : language of the future
 
Scala in Practice
Scala in PracticeScala in Practice
Scala in Practice
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Development
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
Ankara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with ScalaAnkara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with Scala
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
 
Functional Programming in Scala
Functional Programming in ScalaFunctional Programming in Scala
Functional Programming in Scala
 
Practically Functional
Practically FunctionalPractically Functional
Practically Functional
 
Functional Algebra: Monoids Applied
Functional Algebra: Monoids AppliedFunctional Algebra: Monoids Applied
Functional Algebra: Monoids Applied
 
Java Keeps Throttling Up!
Java Keeps Throttling Up!Java Keeps Throttling Up!
Java Keeps Throttling Up!
 
The Evolution of Scala / Scala進化論
The Evolution of Scala / Scala進化論The Evolution of Scala / Scala進化論
The Evolution of Scala / Scala進化論
 
scala.reflect, Eugene Burmako
scala.reflect, Eugene Burmakoscala.reflect, Eugene Burmako
scala.reflect, Eugene Burmako
 
A Scala Corrections Library
A Scala Corrections LibraryA Scala Corrections Library
A Scala Corrections Library
 

Viewers also liked

Aturansinus
AturansinusAturansinus
Aturansinusaan72
 
Functional Scala II (in practice)
Functional Scala II (in practice)Functional Scala II (in practice)
Functional Scala II (in practice)Mario Gleichmann
 
Scala 2.10.0 (english version)
Scala 2.10.0 (english version)Scala 2.10.0 (english version)
Scala 2.10.0 (english version)Daniel Sobral
 
Intro to pattern matching in scala
Intro to pattern matching in scalaIntro to pattern matching in scala
Intro to pattern matching in scalaJan Krag
 
Scala Workshop
Scala WorkshopScala Workshop
Scala WorkshopClueda AG
 
Scala Programming for Semantic Web Developers ESWC Semdev2015
Scala Programming for Semantic Web Developers ESWC Semdev2015Scala Programming for Semantic Web Developers ESWC Semdev2015
Scala Programming for Semantic Web Developers ESWC Semdev2015Jean-Paul Calbimonte
 
Scala for Java Developers (Silicon Valley Code Camp 13)
Scala for Java Developers (Silicon Valley Code Camp 13)Scala for Java Developers (Silicon Valley Code Camp 13)
Scala for Java Developers (Silicon Valley Code Camp 13)Ramnivas Laddad
 
Scala For Java Programmers
Scala For Java ProgrammersScala For Java Programmers
Scala For Java ProgrammersEnno Runne
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 
Develop realtime web with Scala and Xitrum
Develop realtime web with Scala and XitrumDevelop realtime web with Scala and Xitrum
Develop realtime web with Scala and XitrumNgoc Dao
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaVladimir Kostyukov
 
Advanced Functional Programming in Scala
Advanced Functional Programming in ScalaAdvanced Functional Programming in Scala
Advanced Functional Programming in ScalaPatrick Nicolas
 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaYevgeniy Brikman
 
Functional Database Strategies at Scala Bay
Functional Database Strategies at Scala BayFunctional Database Strategies at Scala Bay
Functional Database Strategies at Scala BayJason Swartz
 
Rexona City Tracks Mobile App Concept
Rexona City Tracks Mobile App ConceptRexona City Tracks Mobile App Concept
Rexona City Tracks Mobile App ConceptJorge Teixeira
 

Viewers also liked (20)

scala
scalascala
scala
 
Aturansinus
AturansinusAturansinus
Aturansinus
 
Functional Scala I
Functional Scala IFunctional Scala I
Functional Scala I
 
Functional Scala II (in practice)
Functional Scala II (in practice)Functional Scala II (in practice)
Functional Scala II (in practice)
 
Pattern Matching in Scala
Pattern Matching in ScalaPattern Matching in Scala
Pattern Matching in Scala
 
Scala 2.10.0 (english version)
Scala 2.10.0 (english version)Scala 2.10.0 (english version)
Scala 2.10.0 (english version)
 
Intro to pattern matching in scala
Intro to pattern matching in scalaIntro to pattern matching in scala
Intro to pattern matching in scala
 
Scala Workshop
Scala WorkshopScala Workshop
Scala Workshop
 
Scala Programming for Semantic Web Developers ESWC Semdev2015
Scala Programming for Semantic Web Developers ESWC Semdev2015Scala Programming for Semantic Web Developers ESWC Semdev2015
Scala Programming for Semantic Web Developers ESWC Semdev2015
 
Scala for Java Developers (Silicon Valley Code Camp 13)
Scala for Java Developers (Silicon Valley Code Camp 13)Scala for Java Developers (Silicon Valley Code Camp 13)
Scala for Java Developers (Silicon Valley Code Camp 13)
 
Scala For Java Programmers
Scala For Java ProgrammersScala For Java Programmers
Scala For Java Programmers
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Develop realtime web with Scala and Xitrum
Develop realtime web with Scala and XitrumDevelop realtime web with Scala and Xitrum
Develop realtime web with Scala and Xitrum
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in Scala
 
Advanced Functional Programming in Scala
Advanced Functional Programming in ScalaAdvanced Functional Programming in Scala
Advanced Functional Programming in Scala
 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and Scala
 
Why Scala?
Why Scala?Why Scala?
Why Scala?
 
Scala Days NYC 2016
Scala Days NYC 2016Scala Days NYC 2016
Scala Days NYC 2016
 
Functional Database Strategies at Scala Bay
Functional Database Strategies at Scala BayFunctional Database Strategies at Scala Bay
Functional Database Strategies at Scala Bay
 
Rexona City Tracks Mobile App Concept
Rexona City Tracks Mobile App ConceptRexona City Tracks Mobile App Concept
Rexona City Tracks Mobile App Concept
 

Similar to Introduction to Scala for Java Developers

Scala + WattzOn, sitting in a tree....
Scala + WattzOn, sitting in a tree....Scala + WattzOn, sitting in a tree....
Scala + WattzOn, sitting in a tree....Raffi Krikorian
 
JavaScript 1.5 to 2.0 (TomTom)
JavaScript 1.5 to 2.0 (TomTom)JavaScript 1.5 to 2.0 (TomTom)
JavaScript 1.5 to 2.0 (TomTom)jeresig
 
Tamarin And Ecmascript 4
Tamarin And Ecmascript 4Tamarin And Ecmascript 4
Tamarin And Ecmascript 4elliando dias
 
Tamarin and ECMAScript 4
Tamarin and ECMAScript 4Tamarin and ECMAScript 4
Tamarin and ECMAScript 4jeresig
 
Java Boilerplate Busters
Java Boilerplate BustersJava Boilerplate Busters
Java Boilerplate BustersHamletDRC
 
Impacta - Show Day de Rails
Impacta - Show Day de RailsImpacta - Show Day de Rails
Impacta - Show Day de RailsFabio Akita
 
JSUG - Scala Lightning Talk by Michael Greifeneder
JSUG - Scala Lightning Talk by Michael GreifenederJSUG - Scala Lightning Talk by Michael Greifeneder
JSUG - Scala Lightning Talk by Michael GreifenederChristoph Pickl
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6Solution4Future
 
Zend framework 05 - ajax, json and j query
Zend framework 05 - ajax, json and j queryZend framework 05 - ajax, json and j query
Zend framework 05 - ajax, json and j queryTricode (part of Dept)
 
Scala for Java Developers
Scala for Java DevelopersScala for Java Developers
Scala for Java DevelopersRamnivasLaddad
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript Everywhereelliando dias
 
Scala - just good for Java shops?
Scala - just good for Java shops?Scala - just good for Java shops?
Scala - just good for Java shops?Sarah Mount
 
Beginning Scala Svcc 2009
Beginning Scala Svcc 2009Beginning Scala Svcc 2009
Beginning Scala Svcc 2009David Pollak
 
All I Need to Know I Learned by Writing My Own Web Framework
All I Need to Know I Learned by Writing My Own Web FrameworkAll I Need to Know I Learned by Writing My Own Web Framework
All I Need to Know I Learned by Writing My Own Web FrameworkBen Scofield
 

Similar to Introduction to Scala for Java Developers (20)

Scala + WattzOn, sitting in a tree....
Scala + WattzOn, sitting in a tree....Scala + WattzOn, sitting in a tree....
Scala + WattzOn, sitting in a tree....
 
Why Scala?
Why Scala?Why Scala?
Why Scala?
 
Scala
ScalaScala
Scala
 
JavaScript 1.5 to 2.0 (TomTom)
JavaScript 1.5 to 2.0 (TomTom)JavaScript 1.5 to 2.0 (TomTom)
JavaScript 1.5 to 2.0 (TomTom)
 
Tamarin And Ecmascript 4
Tamarin And Ecmascript 4Tamarin And Ecmascript 4
Tamarin And Ecmascript 4
 
Tamarin and ECMAScript 4
Tamarin and ECMAScript 4Tamarin and ECMAScript 4
Tamarin and ECMAScript 4
 
Java Boilerplate Busters
Java Boilerplate BustersJava Boilerplate Busters
Java Boilerplate Busters
 
Impacta - Show Day de Rails
Impacta - Show Day de RailsImpacta - Show Day de Rails
Impacta - Show Day de Rails
 
JSUG - Scala Lightning Talk by Michael Greifeneder
JSUG - Scala Lightning Talk by Michael GreifenederJSUG - Scala Lightning Talk by Michael Greifeneder
JSUG - Scala Lightning Talk by Michael Greifeneder
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
 
Jquery 1
Jquery 1Jquery 1
Jquery 1
 
Zend framework 05 - ajax, json and j query
Zend framework 05 - ajax, json and j queryZend framework 05 - ajax, json and j query
Zend framework 05 - ajax, json and j query
 
Scala for Java Developers
Scala for Java DevelopersScala for Java Developers
Scala for Java Developers
 
Scala presentationjune112011
Scala presentationjune112011Scala presentationjune112011
Scala presentationjune112011
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript Everywhere
 
All That Jazz
All  That  JazzAll  That  Jazz
All That Jazz
 
Scala - just good for Java shops?
Scala - just good for Java shops?Scala - just good for Java shops?
Scala - just good for Java shops?
 
Rack Middleware
Rack MiddlewareRack Middleware
Rack Middleware
 
Beginning Scala Svcc 2009
Beginning Scala Svcc 2009Beginning Scala Svcc 2009
Beginning Scala Svcc 2009
 
All I Need to Know I Learned by Writing My Own Web Framework
All I Need to Know I Learned by Writing My Own Web FrameworkAll I Need to Know I Learned by Writing My Own Web Framework
All I Need to Know I Learned by Writing My Own Web Framework
 

More from Michael Galpin

Android lessons you won't learn in school
Android lessons you won't learn in schoolAndroid lessons you won't learn in school
Android lessons you won't learn in schoolMichael Galpin
 
Design Patterns for Tablets and Smartphones
Design Patterns for Tablets and SmartphonesDesign Patterns for Tablets and Smartphones
Design Patterns for Tablets and SmartphonesMichael Galpin
 
Scala on Android: Experiences at Bump Technologies
Scala on Android: Experiences at Bump TechnologiesScala on Android: Experiences at Bump Technologies
Scala on Android: Experiences at Bump TechnologiesMichael Galpin
 
That’s My App - Running in Your Background - Draining Your Battery
That’s My App - Running in Your Background - Draining Your BatteryThat’s My App - Running in Your Background - Draining Your Battery
That’s My App - Running in Your Background - Draining Your BatteryMichael Galpin
 
Persistent Data Structures And Managed References
Persistent Data Structures And Managed ReferencesPersistent Data Structures And Managed References
Persistent Data Structures And Managed ReferencesMichael Galpin
 
Mobile Development 101
Mobile Development 101Mobile Development 101
Mobile Development 101Michael Galpin
 
RIAs Done Right: Grails, Flex, and EXT GWT
RIAs Done Right: Grails, Flex, and EXT GWTRIAs Done Right: Grails, Flex, and EXT GWT
RIAs Done Right: Grails, Flex, and EXT GWTMichael Galpin
 

More from Michael Galpin (12)

Android lessons you won't learn in school
Android lessons you won't learn in schoolAndroid lessons you won't learn in school
Android lessons you won't learn in school
 
Design Patterns for Tablets and Smartphones
Design Patterns for Tablets and SmartphonesDesign Patterns for Tablets and Smartphones
Design Patterns for Tablets and Smartphones
 
Android workshop
Android workshopAndroid workshop
Android workshop
 
Scala on Android: Experiences at Bump Technologies
Scala on Android: Experiences at Bump TechnologiesScala on Android: Experiences at Bump Technologies
Scala on Android: Experiences at Bump Technologies
 
That’s My App - Running in Your Background - Draining Your Battery
That’s My App - Running in Your Background - Draining Your BatteryThat’s My App - Running in Your Background - Draining Your Battery
That’s My App - Running in Your Background - Draining Your Battery
 
Mobile Web 5.0
Mobile Web 5.0Mobile Web 5.0
Mobile Web 5.0
 
Persistent Data Structures And Managed References
Persistent Data Structures And Managed ReferencesPersistent Data Structures And Managed References
Persistent Data Structures And Managed References
 
Scala on Your Phone
Scala on Your PhoneScala on Your Phone
Scala on Your Phone
 
Mobile Development 101
Mobile Development 101Mobile Development 101
Mobile Development 101
 
RIAs Done Right: Grails, Flex, and EXT GWT
RIAs Done Right: Grails, Flex, and EXT GWTRIAs Done Right: Grails, Flex, and EXT GWT
RIAs Done Right: Grails, Flex, and EXT GWT
 
Eclipse @eBay 2009
Eclipse @eBay 2009Eclipse @eBay 2009
Eclipse @eBay 2009
 
Eclipse@eBay
Eclipse@eBayEclipse@eBay
Eclipse@eBay
 

Recently uploaded

AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarPrecisely
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding TeamAdam Moalla
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdfPedro Manuel
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxMatsuo Lab
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesMd Hossain Ali
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024SkyPlanner
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024D Cloud Solutions
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsSeth Reyes
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Commit University
 
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsIgniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsSafe Software
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioChristian Posta
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfAijun Zhang
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8DianaGray10
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.YounusS2
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxUdaiappa Ramachandran
 

Recently uploaded (20)

AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity Webinar
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdf
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptx
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
 
20230104 - machine vision
20230104 - machine vision20230104 - machine vision
20230104 - machine vision
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and Hazards
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)
 
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsIgniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and Istio
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdf
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptx
 

Introduction to Scala for Java Developers

  • 1. Scala for Java Developers Michael Galpin, http://fupeg.blogspot.com Tuesday, January 13, 2009
  • 2. Scala is... A general purpose programming language ✤ A language that runs on the Java VM ✤ Statically typed ✤ An object-oriented language ✤ No primitives or operators, but with singletons ✤ A functional language ✤ A scalable language ✤ Tuesday, January 13, 2009
  • 3. Scala is General Purpose Some uses of Scala ✤ Scripting ✤ Web applications ✤ Messaging ✤ Graphical User Interfaces ✤ Tuesday, January 13, 2009
  • 4. Scala runs on the JVM Compiles to Java bytecode ✤ Written by Martin Odersky (javac) ✤ Uses core Java heavily ✤ Can call any Java classes ✤ Can be called by any Java class ✤ Tuesday, January 13, 2009
  • 5. Scala is Statically Typed var name :String = quot;Hello, worldquot; ; Tuesday, January 13, 2009
  • 6. Scala is Statically Typed var name = quot;Hello, worldquot; ; Tuesday, January 13, 2009
  • 7. Scala is Statically Typed var name = quot;Hello, worldquot; Tuesday, January 13, 2009
  • 8. Scala is Statically Typed val name = quot;Hello, worldquot; Tuesday, January 13, 2009
  • 9. Scala is Statically Typed val name = quot;Hello, worldquot; def makeList(a:String, b:String):List[String] = { return a :: b :: Nil ; } Tuesday, January 13, 2009
  • 10. Scala is Statically Typed val name = quot;Hello, worldquot; def makeList(a:String, b:String):List[String] = { return a :: b :: Nil } Tuesday, January 13, 2009
  • 11. Scala is Statically Typed val name = quot;Hello, worldquot; def makeList(a:String, b:String):List[String] = { a :: b :: Nil } Tuesday, January 13, 2009
  • 12. Scala is Statically Typed val name = quot;Hello, worldquot; def makeList(a:String, b:String):List[String] = a :: b :: Nil Tuesday, January 13, 2009
  • 13. Scala is Statically Typed val name = quot;Hello, worldquot; def makeList(a:String, b:String) = a :: b :: Nil Tuesday, January 13, 2009
  • 14. Scala is object-oriented Classes ✤ class Computer (val clockSpeed:Double, var memory:Int, var hdd:Int, var os:String){ def this(clockSpeed:Double) = this(clockSpeed, 0, 0, null) def addMemory(newRam:Int):Unit = { this.memory += newRam } def addDrive(newHdd:Int) = { this.hdd += newHdd } override def toString = clockSpeed + quot; GHz quot; + memory + quot; GB RAM quot; + hdd + quot; GB hdd quot; + os } Tuesday, January 13, 2009
  • 15. Scala is object-oriented Inheritance ✤ class Laptop(clockSpeed:Double, memory:Int, hdd:Int, val screenSize:Int, os:String) extends Computer(clockSpeed,memory,hdd,os){ override def toString = screenSize + quot; inch screen quot; + super.toString } Mix-ins ✤ trait Mac{ var osVersion:String def osx = { osVersion match { case quot;10.5quot; => quot;Leopardquot; case quot;10.4quot; => quot;Tigerquot; case _ => quot;OSXquot; } } } class MacBook(clockSpeed:Double, memory:Int, hdd:Int, os:String) extends Laptop(clockSpeed, memory, hdd, 13, os) with Mac{ var osVersion = os } Tuesday, January 13, 2009
  • 16. Scala has More Effective Java Tuesday, January 13, 2009
  • 17. Scala has More Effective Java You always override equals, hashCode, and toString ... right? ✤ Tuesday, January 13, 2009
  • 18. Scala has More Effective Java You always override equals, hashCode, and toString ... right? ✤ Case Classes ✤ case class Player(val name:String, val team:String, val position:String) val tebow = Player(quot;Tim Tebowquot;,quot;Floridaquot;,quot;QBquot;) println(tebow) // prints (Time Tebow,Florida,QB) val clone = Player(quot;Tim Tebowquot;,quot;Floridaquot;,quot;QBquot;) println(clone == tebow) // prints true val set = new HashSet[Player] set += tebow set += clone println(set.size) // prints 1 Tuesday, January 13, 2009
  • 19. Scala is very object-oriented No primitives ✤ No int, just Int ✤ No String[], just Array[String] ✤ No operators ✤ + - * / ++ += are all just methods ✤ Create your own or overload (if not final) ✤ Tuesday, January 13, 2009
  • 20. No Operators, Just Methods Tuesday, January 13, 2009
  • 21. No Operators, Just Methods Dots and parentheses are optional ✤ val x = 1.+(2) val y = 1 + 2 println(x == y) // prints true Tuesday, January 13, 2009
  • 22. No Operators, Just Methods Dots and parentheses are optional ✤ val x = 1.+(2) val y = 1 + 2 println(x == y) // prints true Sweet Syntactic Sugar ✤ val cache = new HashMap[String, String] cache += (quot;fooquot;,quot;barquot;) cache -= quot;fooquot; Tuesday, January 13, 2009
  • 23. Great for DSLs Domain Specific Languages ✤ XML ✤ Actors ✤ Tuesday, January 13, 2009
  • 24. XML Example: Atom class Entry(var title:String, val link:String, val id:String, var updated:Date, var summary:String){ def toAtom = <entry> <link href={link}/> <id>{id}</id> <updated>{updated}</updated> <summary>{summary}</summary> </entry> } Tuesday, January 13, 2009
  • 25. XML Example: Atom class Feed(val title:String, val link:String, var updated:Date, val author:String, val id:String){ var entries:List[Entry] = Nil def addEntry(entry:Entry){ entries = entry :: entries } def toAtom = <feed> <title>{title}</title> <link href={link}/> <updated>{updated}</updated> <author> <name>{author}</name> </author> <id>{id}</id> { val nodes = new NodeBuffer for (entry <- entries) { nodes &+ entry.toAtom } nodes } </feed> } Tuesday, January 13, 2009
  • 26. XML Example: Atom object Atom{ def main(args:Array[String]){ val f = new Feed(quot;Programming and Politicsquot;, quot;http://fupeg.blogspot.comquot;, new Date(),quot;Michel Galpinquot;,quot;5819005quot;) val e = new Entry(quot;New Scala Articlequot;, quot;http://fupeg.blogspot.com/2008/04/new-scala-article.htmlquot;, quot;6009113042595594848quot;, new Date(), quot;Article on Scala and XMLquot; ) f.addEntry(e) println(f.toAtom) } } Tuesday, January 13, 2009
  • 27. XML Example: Atom $ scalac Atom.scala $ scala Atom <feed> <title>Programming and Politics</title> <link href=quot;http://fupeg.blogspot.comquot;></link> <updated>Tue Jan 13 11:35:51 PST 2009</updated> <author> <name>Michel Galpin</name> </author> <id>5819005</id> <entry> <link href=quot;http://fupeg.blogspot.com/2008/04/new-scala-article.htmlquot;></link> <id>6009113042595594848</id> <updated>Tue Jan 13 11:35:51 PST 2009</updated> <summary>Scala is good</summary> </entry> </feed> Tuesday, January 13, 2009
  • 28. Singletons in Scala Use object instead of class ✤ object ComputerStore{ def main(args:Array[String]) = { val newton = new MacBook(2.0, 2048, 120, quot;10.5quot;) println(newton.clockSpeed + quot; is fast!quot;) println(quot;newton is running quot; + newton.osx) } } Often used as factories a.k.a. companion objects ✤ val names = List(quot;Billquot;, quot;Davidquot;, quot;Michaelquot;) Tuesday, January 13, 2009
  • 29. Scala is functional A function is an object, its definition is its apply method ✤ object DotProdct{ def apply(list1:List[Number], list2:[Number]) = { var result = 0 for (i <- 0 until list1.size){ result += list1(i)*list2(i) } result } } val a = List(1,2,3) val b = List(4,5,6) println(DotProduct(a,b)) // prints 32 Tuesday, January 13, 2009
  • 30. Closures Functions can be passed as parameters to other functions ✤ Scala allows for inline (anonymous) functions ✤ Still statically typed ✤ Lexically scoped (anonymous or not) ✤ Tuesday, January 13, 2009
  • 32. Closure Examples class Person(val firstName:String, val middleName:String, var lastName:String){ def print( formatter:(String,String,String) => String )={ val str = formatter(firstName,middleName,lastName) println(str) } } Tuesday, January 13, 2009
  • 33. Closure Examples class Person(val firstName:String, val middleName:String, var lastName:String){ def print( formatter:(String,String,String) => String )={ val str = formatter(firstName,middleName,lastName) println(str) } } val p = new Person(quot;Michaelquot;,quot;Davidquot;,quot;Galpinquot;) Tuesday, January 13, 2009
  • 34. Closure Examples class Person(val firstName:String, val middleName:String, var lastName:String){ def print( formatter:(String,String,String) => String )={ val str = formatter(firstName,middleName,lastName) println(str) } } val p = new Person(quot;Michaelquot;,quot;Davidquot;,quot;Galpinquot;) val sep = quot; quot; def std(a:String,b:String,c:String) = List(a,b,c).mkString(sep) p.print(std) Tuesday, January 13, 2009
  • 35. Closure Examples class Person(val firstName:String, val middleName:String, var lastName:String){ def print( formatter:(String,String,String) => String )={ val str = formatter(firstName,middleName,lastName) println(str) } } val p = new Person(quot;Michaelquot;,quot;Davidquot;,quot;Galpinquot;) val sep = quot; quot; def std(a:String,b:String,c:String) = List(a,b,c).mkString(sep) p.print(std) val sep2 = quot;:quot; p.print( (a,b,c) => a + sep + b + sep2 + c) Tuesday, January 13, 2009
  • 36. Closure Examples class Person(val firstName:String, val middleName:String, var lastName:String){ def print( formatter:(String,String,String) => String )={ val str = formatter(firstName,middleName,lastName) println(str) } } val p = new Person(quot;Michaelquot;,quot;Davidquot;,quot;Galpinquot;) val sep = quot; quot; def std(a:String,b:String,c:String) = List(a,b,c).mkString(sep) p.print(std) val sep2 = quot;:quot; p.print( (a,b,c) => a + sep + b + sep2 + c) p.print(_ + sep + _ + sep2 + _) Tuesday, January 13, 2009
  • 37. Closures: Not Just for Golf Tuesday, January 13, 2009
  • 38. Closures: Not Just for Golf var nums = 1 until 100 filter(_ % 3 == 0) Tuesday, January 13, 2009
  • 39. Closures: Not Just for Golf var nums = 1 until 100 filter(_ % 3 == 0) nums.foreach(println(_)) Tuesday, January 13, 2009
  • 40. Closures: Not Just for Golf var nums = 1 until 100 filter(_ % 3 == 0) nums.foreach(println(_)) nums = nums.map(2*_ + 3) println(quot;All greater than 10? quot; + nums.forall(_ > 10)) Tuesday, January 13, 2009
  • 41. Closures: Not Just for Golf var nums = 1 until 100 filter(_ % 3 == 0) nums.foreach(println(_)) nums = nums.map(2*_ + 3) println(quot;All greater than 10? quot; + nums.forall(_ > 10)) val sum = nums.foldLeft(0)(_+_) println(quot;sum=quot;+sum) Tuesday, January 13, 2009
  • 42. Closures: Not Just for Golf var nums = 1 until 100 filter(_ % 3 == 0) nums.foreach(println(_)) nums = nums.map(2*_ + 3) println(quot;All greater than 10? quot; + nums.forall(_ > 10)) val sum = nums.foldLeft(0)(_+_) println(quot;sum=quot;+sum) val sorted = nums.toList.sort( (n,m) => { val remN = n % 5 val remM = m % 5 remN > remM }) sorted.foreach( (i) => println(i + quot; quot; + i % 5)) Tuesday, January 13, 2009
  • 43. Scala: A Scalable Language Compiles to bytecode ✤ Very close to “native” Java ✤ Sometimes faster! ✤ Tail recursion ✤ Concurrency ✤ Tuesday, January 13, 2009
  • 44. Scala: Better Bytecode What is the first triangle number to have at least N divisors? Time N Tuesday, January 13, 2009
  • 45. Tail Recursion: Scala Factorial object Factorial{ val ZERO = BigInt.int2bigInt(0) val ONE = BigInt.int2bigInt(1) def factorial(n:BigInt):BigInt= n match { case ZERO => ONE case ONE => ONE case _ => n*factorial(n-1) } def main(args:Array[String]){ val i = args(0).toInt val n = BigInt.int2bigInt(i) val start = new java.util.Date println(factorial(n)) val duration = (new java.util.Date()).getTime - start.getTime println(quot;duration=quot;+duration) } } Tuesday, January 13, 2009
  • 46. And in Java... import java.math.BigInteger; import java.util.Date; public class Factorial{ public static BigInteger factorial(BigInteger n){ if (n.equals(BigInteger.ZERO)) return BigInteger.ONE; else if (n.equals(BigInteger.ONE)) return BigInteger.ONE; else return n.multiply(factorial(n.subtract(BigInteger.ONE))); } public static void main(String[] args){ BigInteger n = new BigInteger(args[0]); Date start = new Date(); System.out.println(factorial(n)); long duration = (new Date()).getTime() - start.getTime(); System.out.println(quot;duration=quot;+duration); } } Tuesday, January 13, 2009
  • 47. And the Results... Factorial 100000 75000 Time(ms) 50000 25000 0 10000 20000 30000 50000 N Java Scala Tuesday, January 13, 2009
  • 49. Scala Concurrency: Actors Actor Model: A Different Way to Implement Concurrency ✤ Tuesday, January 13, 2009
  • 50. Scala Concurrency: Actors Actor Model: A Different Way to Implement Concurrency ✤ Each Object is an Actor ✤ Tuesday, January 13, 2009
  • 51. Scala Concurrency: Actors Actor Model: A Different Way to Implement Concurrency ✤ Each Object is an Actor ✤ Each Actor has a Mailbox ✤ Tuesday, January 13, 2009
  • 52. Scala Concurrency: Actors Actor Model: A Different Way to Implement Concurrency ✤ Each Object is an Actor ✤ Each Actor has a Mailbox ✤ Actors (Asynchronously) Send Messages and Receive them in their ✤ Mailbox Tuesday, January 13, 2009
  • 53. Scala Concurrency: Actors Actor Model: A Different Way to Implement Concurrency ✤ Each Object is an Actor ✤ Each Actor has a Mailbox ✤ Actors (Asynchronously) Send Messages and Receive them in their ✤ Mailbox No Shared State ✤ Tuesday, January 13, 2009
  • 54. Why Actors: Performance Apache (C/Threads) vs. Yaws (Erlang/Actors) Throughput (KB/s) Concurrent Sessions Tuesday, January 13, 2009
  • 55. Why Actors: Simpler Code No Code Changes for Multi-threaded vs. Single-threaded ✤ No Mutable State ✤ No (Dead) Locking ✤ Tuesday, January 13, 2009
  • 56. Actor Example case object Ping case object Pong case object Stop class Pong extends Actor { def act() { var pongCount = 0 loop { react { case Ping => if (pongCount % 1000 == 0) // print every 1000th Ping println(quot;Pong: ping quot;+pongCount) sender ! Pong pongCount = pongCount + 1 case Stop => println(quot;Pong: stopquot;) exit() } } } } Tuesday, January 13, 2009
  • 57. Actor Example class Ping(count: Int, pong: Actor) extends Actor { def act(){ var pingsLeft = count - 1 pong ! Ping loop{ react { case Pong => if (pingsLeft % 1000 == 0) // print every 1000th Pong println(quot;Ping: pongquot;) if (pingsLeft > 0){ pong ! Ping pingsLeft -= 1 } else { println(quot;Ping: stopquot;) pong ! Stop exit() } } } } } Tuesday, January 13, 2009
  • 58. Actor Example object PingPong { def main(args:Array[String]){ val pong = new Pong val ping = new Ping(100000, pong) ping.start pong.start } } Tuesday, January 13, 2009