SlideShare a Scribd company logo
1 of 24
Download to read offline
Scala coated JVM
@ Joint meeting of Java User Group Scotland
            and Scala Scotland


            Stuart Roebuck
            stuart.roebuck@proinnovate.com
The basics…

• Created by Martin Odersky (EPFL)
• JVM
• Object oriented and functional
• ‘scalable language’
• Scala 1.0—late 2003
• Scala 2.8.0—July 2010
“If I were to pick a language to
use today other than Java, it
would be Scala”
                   James Gosling
Commercial users of Scala
•   Twitter—Scala back end Ruby front end
•   LinkedIn
•   Foursquare—Scala and Lift
•   Siemens—Scala and Lift
•   SAP
•   EDF
•   Sony Pictures (ImageWorks)
•   Nature Magazine
•   TomTom
•   …and Google
Try this at home!

• Scala home: http://www.scala-lang.org/
• Downloadable for Mac, Linux & Windows
• Shell interpreter: scala
• Compilers: scalac and fsc
• Documentation generator scaladoc
• Plugins for Eclipse, Netbeans, IntelliJ
• Popular build tool “sbt” (simple-build-tool)
Demo 1
Scripting with Scala
Email extraction shell script
#! /bin/sh
exec scala "$0" "$@"
!#

import scala.io.Source

val email = """[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}""".r
val filtered = Source.stdin.getLines.
     flatMap( email.findAllIn(_)).
     map(_.toLowerCase).toSet.toList.sortWith(_<_)

filtered.foreach{ println(_) }
How does Scala differ
             from Java?

•   Everything is an object   •   Pattern matching and
                                  Extractors
•   First-class functions
    (‘closures’)              •   XML literals
•   Singleton objects         •   Case classes
•   Mixin composition         •   Lazy evaluation
    with Traits               •   Tuples
Everything is an object
“Answer = ” + 6 * 4

“Answer = ”.+((6).*(4))
First class functions
def time(f: => Unit): Double = {
  val start = System.nanoTime
  f
  val end = System.nanoTime
  (end - start) / 1000000.0
}


val timeTaken = time {
  Thread.sleep(100)
}
Singleton Objects (Java)
public class Singleton {

    private Singleton() {
    }

    private static class SingletonHolder {
      public static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
      return SingletonHolder.INSTANCE;
    }

}
Singleton Objects (Scala)
object Singleton {
  val name = “This is a Singleton Object”
}
Traits / Mix-in Composition
class Executor(f: () => Unit) {
   def exec() { f() }
}
trait Logging extends Executor {
   override def exec() {
       println("Executing...")
       super.exec()
   }
}
trait Timing extends Executor {
   override def exec() {
       val start = System.currentTimeMillis
       super.exec()
       val end = System.currentTimeMillis
       printf("==> Time taken: %d ms%n", end-start)
   }
}

val e = new Executor(() => println("Hello")) with Timing with Logging
e.exec
Executing...
Hello
==> Time taken: 0 ms
Pattern Matching
def intToString(value: Any) = value match {
  case x:Int => x.toString
  case (x:Int) :: y => x.toString
  case Some(x:Int) => x.toString
  case _ => ""
}

scala> intToString(23)
res1: java.lang.String = 23

scala> intToString(List(23,45))
res2: java.lang.String = 23

scala> intToString(Some(11))
res3: java.lang.String = 11

scala> intToString(Some("String"))
res4: java.lang.String =
Demo 2
e Scala REPL(Read Eval Print Loop)
BigInteger / BigInt Factorial
import java.math.BigInteger

def factorial(x: BigInteger): BigInteger =
  if (x == BigInteger.ZERO)
     BigInteger.ONE
  else
     x.multiply(factorial(x.subtract(BigInteger.ONE)))



def factorial(x: BigInt): BigInt =
  if (x == 0) 1 else x * factorial(x - 1)
BigInt Definition
class BigInt(val bigInteger: BigInteger) extends java.lang.Number {

  override def hashCode(): Int = this.bigInteger.hashCode()

  override def equals (that: Any): Boolean = that match {
    case that: BigInt => this equals that
    case that: java.lang.Double => this.bigInteger.doubleValue == that.doubleValue
    case that: java.lang.Float => this.bigInteger.floatValue == that.floatValue
    case that: java.lang.Number => this equals BigInt(that.longValue)
    case that: java.lang.Character => this equals BigInt(that.charValue.asInstanceOf[Int])
    case _ => false
  }

  def   equals (that: BigInt): Boolean = this.bigInteger.compareTo(that.bigInteger) == 0
  def   compare (that: BigInt): Int = this.bigInteger.compareTo(that.bigInteger)
  def   <= (that: BigInt): Boolean = this.bigInteger.compareTo(that.bigInteger) <= 0
  def   >= (that: BigInt): Boolean = this.bigInteger.compareTo(that.bigInteger) >= 0
  def   < (that: BigInt): Boolean = this.bigInteger.compareTo(that.bigInteger) < 0
  def   > (that: BigInt): Boolean = this.bigInteger.compareTo(that.bigInteger) > 0
  def   + (that: BigInt): BigInt = new BigInt(this.bigInteger.add(that.bigInteger))
  …
Implicit conversion
scala> factorial(10)
res0: BigInt = 3628800



implicit def int2bigInt(i: Int): BigInt = BigInt(i)



def factorial(x: BigInt): BigInt = …



scala> factorial(int2bigInt(10))
res0: BigInt = 3628800
Pattern matching
scala> val Email = """([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+.[a-zA-Z]
{2,4})""".r
Email: scala.util.matching.Regex = ([a-zA-Z0-9._%+-]+)@([a-zA-
Z0-9.-]+.[a-zA-Z]{2,4})

scala> val Email(name,address) = "stuart.roebuck@proinnovate.com"
name: String = stuart.roebuck
address: String = proinnovate.com
Demo 3
Building a Scala project with sbt
Questions?
Build tools +
• Maven Plugin (no endorsement implied)—http://
  scala-tools.org/mvnsites/maven-scala-plugin/
• simple-build-tool—http://code.google.com/p/
  simple-build-tool/
• Apache Ant tasks for Scala—http://www.scala-
  lang.org/node/98
• Apache Buildr—http://buildr.apache.org/
• JavaRebel—http://www.zeroturnaround.com/
  jrebel/

More Related Content

What's hot

Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008
Yardena Meymann
 
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scala
akuklev
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 

What's hot (20)

Scala introduction
Scala introductionScala introduction
Scala introduction
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Metaprogramming  in Scala 2.10, Eugene Burmako, Metaprogramming  in Scala 2.10, Eugene Burmako,
Metaprogramming in Scala 2.10, Eugene Burmako,
 
The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at Twitter
 
Introduction to Scala for Java Developers
Introduction to Scala for Java DevelopersIntroduction to Scala for Java Developers
Introduction to Scala for Java Developers
 
All about scala
All about scalaAll about scala
All about scala
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in Scala
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Scala test
Scala testScala test
Scala test
 
Java 7 New Features
Java 7 New FeaturesJava 7 New Features
Java 7 New Features
 
Scale up your thinking
Scale up your thinkingScale up your thinking
Scale up your thinking
 
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scala
 
Scala for scripting
Scala for scriptingScala for scripting
Scala for scripting
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Scala in Practice
Scala in PracticeScala in Practice
Scala in Practice
 

Viewers also liked (7)

Buildstore Pres Lorraine
Buildstore Pres LorraineBuildstore Pres Lorraine
Buildstore Pres Lorraine
 
Onnivori vegetariani vegani il dibattito è aperto 19 aprile 2012
Onnivori vegetariani vegani il dibattito è aperto 19 aprile 2012Onnivori vegetariani vegani il dibattito è aperto 19 aprile 2012
Onnivori vegetariani vegani il dibattito è aperto 19 aprile 2012
 
Mangiare bene fa male e 21 marzo 2012 light
Mangiare bene fa male e 21 marzo 2012 lightMangiare bene fa male e 21 marzo 2012 light
Mangiare bene fa male e 21 marzo 2012 light
 
Dove Evolution
Dove EvolutionDove Evolution
Dove Evolution
 
Blogger2008
Blogger2008Blogger2008
Blogger2008
 
Subversive talk - Eclipse Summit Europe 2008
Subversive talk - Eclipse Summit Europe 2008Subversive talk - Eclipse Summit Europe 2008
Subversive talk - Eclipse Summit Europe 2008
 
Metsloomad
MetsloomadMetsloomad
Metsloomad
 

Similar to Scala coated JVM

(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
Tomasz Wrobel
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
shinolajla
 
Clojure - A new Lisp
Clojure - A new LispClojure - A new Lisp
Clojure - A new Lisp
elliando dias
 
Intro to scala
Intro to scalaIntro to scala
Intro to scala
Joe Zulli
 

Similar to Scala coated JVM (20)

Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risks
 
Introduction to scala
Introduction to scalaIntroduction to scala
Introduction to scala
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
Functional Object-Oriented Imperative Scala / 関数型オブジェクト指向命令型 Scala by Sébasti...
Functional Object-Oriented Imperative Scala / 関数型オブジェクト指向命令型 Scala by Sébasti...Functional Object-Oriented Imperative Scala / 関数型オブジェクト指向命令型 Scala by Sébasti...
Functional Object-Oriented Imperative Scala / 関数型オブジェクト指向命令型 Scala by Sébasti...
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 
Clojure - A new Lisp
Clojure - A new LispClojure - A new Lisp
Clojure - A new Lisp
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
Intro to scala
Intro to scalaIntro to scala
Intro to scala
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
 

Recently uploaded

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 

Scala coated JVM

  • 1. Scala coated JVM @ Joint meeting of Java User Group Scotland and Scala Scotland Stuart Roebuck stuart.roebuck@proinnovate.com
  • 2. The basics… • Created by Martin Odersky (EPFL) • JVM • Object oriented and functional • ‘scalable language’ • Scala 1.0—late 2003 • Scala 2.8.0—July 2010
  • 3. “If I were to pick a language to use today other than Java, it would be Scala” James Gosling
  • 4. Commercial users of Scala • Twitter—Scala back end Ruby front end • LinkedIn • Foursquare—Scala and Lift • Siemens—Scala and Lift • SAP • EDF • Sony Pictures (ImageWorks) • Nature Magazine • TomTom • …and Google
  • 5. Try this at home! • Scala home: http://www.scala-lang.org/ • Downloadable for Mac, Linux & Windows • Shell interpreter: scala • Compilers: scalac and fsc • Documentation generator scaladoc • Plugins for Eclipse, Netbeans, IntelliJ • Popular build tool “sbt” (simple-build-tool)
  • 7. Email extraction shell script #! /bin/sh exec scala "$0" "$@" !# import scala.io.Source val email = """[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}""".r val filtered = Source.stdin.getLines. flatMap( email.findAllIn(_)). map(_.toLowerCase).toSet.toList.sortWith(_<_) filtered.foreach{ println(_) }
  • 8. How does Scala differ from Java? • Everything is an object • Pattern matching and Extractors • First-class functions (‘closures’) • XML literals • Singleton objects • Case classes • Mixin composition • Lazy evaluation with Traits • Tuples
  • 9. Everything is an object “Answer = ” + 6 * 4 “Answer = ”.+((6).*(4))
  • 10. First class functions def time(f: => Unit): Double = { val start = System.nanoTime f val end = System.nanoTime (end - start) / 1000000.0 } val timeTaken = time { Thread.sleep(100) }
  • 11. Singleton Objects (Java) public class Singleton { private Singleton() { } private static class SingletonHolder { public static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.INSTANCE; } }
  • 12. Singleton Objects (Scala) object Singleton { val name = “This is a Singleton Object” }
  • 13. Traits / Mix-in Composition class Executor(f: () => Unit) { def exec() { f() } } trait Logging extends Executor { override def exec() { println("Executing...") super.exec() } } trait Timing extends Executor { override def exec() { val start = System.currentTimeMillis super.exec() val end = System.currentTimeMillis printf("==> Time taken: %d ms%n", end-start) } } val e = new Executor(() => println("Hello")) with Timing with Logging e.exec Executing... Hello ==> Time taken: 0 ms
  • 14. Pattern Matching def intToString(value: Any) = value match { case x:Int => x.toString case (x:Int) :: y => x.toString case Some(x:Int) => x.toString case _ => "" } scala> intToString(23) res1: java.lang.String = 23 scala> intToString(List(23,45)) res2: java.lang.String = 23 scala> intToString(Some(11)) res3: java.lang.String = 11 scala> intToString(Some("String")) res4: java.lang.String =
  • 15. Demo 2 e Scala REPL(Read Eval Print Loop)
  • 16. BigInteger / BigInt Factorial import java.math.BigInteger def factorial(x: BigInteger): BigInteger = if (x == BigInteger.ZERO) BigInteger.ONE else x.multiply(factorial(x.subtract(BigInteger.ONE))) def factorial(x: BigInt): BigInt = if (x == 0) 1 else x * factorial(x - 1)
  • 17. BigInt Definition class BigInt(val bigInteger: BigInteger) extends java.lang.Number { override def hashCode(): Int = this.bigInteger.hashCode() override def equals (that: Any): Boolean = that match { case that: BigInt => this equals that case that: java.lang.Double => this.bigInteger.doubleValue == that.doubleValue case that: java.lang.Float => this.bigInteger.floatValue == that.floatValue case that: java.lang.Number => this equals BigInt(that.longValue) case that: java.lang.Character => this equals BigInt(that.charValue.asInstanceOf[Int]) case _ => false } def equals (that: BigInt): Boolean = this.bigInteger.compareTo(that.bigInteger) == 0 def compare (that: BigInt): Int = this.bigInteger.compareTo(that.bigInteger) def <= (that: BigInt): Boolean = this.bigInteger.compareTo(that.bigInteger) <= 0 def >= (that: BigInt): Boolean = this.bigInteger.compareTo(that.bigInteger) >= 0 def < (that: BigInt): Boolean = this.bigInteger.compareTo(that.bigInteger) < 0 def > (that: BigInt): Boolean = this.bigInteger.compareTo(that.bigInteger) > 0 def + (that: BigInt): BigInt = new BigInt(this.bigInteger.add(that.bigInteger)) …
  • 18. Implicit conversion scala> factorial(10) res0: BigInt = 3628800 implicit def int2bigInt(i: Int): BigInt = BigInt(i) def factorial(x: BigInt): BigInt = … scala> factorial(int2bigInt(10)) res0: BigInt = 3628800
  • 19. Pattern matching scala> val Email = """([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+.[a-zA-Z] {2,4})""".r Email: scala.util.matching.Regex = ([a-zA-Z0-9._%+-]+)@([a-zA- Z0-9.-]+.[a-zA-Z]{2,4}) scala> val Email(name,address) = "stuart.roebuck@proinnovate.com" name: String = stuart.roebuck address: String = proinnovate.com
  • 20. Demo 3 Building a Scala project with sbt
  • 21.
  • 23.
  • 24. Build tools + • Maven Plugin (no endorsement implied)—http:// scala-tools.org/mvnsites/maven-scala-plugin/ • simple-build-tool—http://code.google.com/p/ simple-build-tool/ • Apache Ant tasks for Scala—http://www.scala- lang.org/node/98 • Apache Buildr—http://buildr.apache.org/ • JavaRebel—http://www.zeroturnaround.com/ jrebel/