SlideShare a Scribd company logo
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
Scala coated JVM
Questions?
Scala coated JVM
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 (20)

PPT
Scala introduction
Yardena Meymann
 
PDF
Scala at HUJI PL Seminar 2008
Yardena Meymann
 
PDF
Spark workshop
Wojciech Pituła
 
ODP
A Tour Of Scala
fanf42
 
PDF
Metaprogramming in Scala 2.10, Eugene Burmako,
Vasil Remeniuk
 
KEY
The Why and How of Scala at Twitter
Alex Payne
 
PDF
Introduction to Scala for Java Developers
Michael Galpin
 
PPTX
All about scala
Yardena Meymann
 
PPT
Scala in a nutshell by venkat
Venkateswaran Kandasamy
 
PPTX
Intro to Functional Programming in Scala
Shai Yallin
 
PPTX
Scala fundamentals
Alfonso Ruzafa
 
PDF
Pragmatic Real-World Scala (short version)
Jonas Bonér
 
PDF
Scala test
Inphina Technologies
 
PDF
Java 7 New Features
Jussi Pohjolainen
 
PPTX
Scale up your thinking
Yardena Meymann
 
PDF
Procedure Typing for Scala
akuklev
 
KEY
Scala for scripting
michid
 
PPT
Scala Talk at FOSDEM 2009
Martin Odersky
 
PDF
scalaliftoff2009.pdf
Hiroshi Ono
 
PDF
Scala in Practice
Francesco Usai
 
Scala introduction
Yardena Meymann
 
Scala at HUJI PL Seminar 2008
Yardena Meymann
 
Spark workshop
Wojciech Pituła
 
A Tour Of Scala
fanf42
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Vasil Remeniuk
 
The Why and How of Scala at Twitter
Alex Payne
 
Introduction to Scala for Java Developers
Michael Galpin
 
All about scala
Yardena Meymann
 
Scala in a nutshell by venkat
Venkateswaran Kandasamy
 
Intro to Functional Programming in Scala
Shai Yallin
 
Scala fundamentals
Alfonso Ruzafa
 
Pragmatic Real-World Scala (short version)
Jonas Bonér
 
Java 7 New Features
Jussi Pohjolainen
 
Scale up your thinking
Yardena Meymann
 
Procedure Typing for Scala
akuklev
 
Scala for scripting
michid
 
Scala Talk at FOSDEM 2009
Martin Odersky
 
scalaliftoff2009.pdf
Hiroshi Ono
 
Scala in Practice
Francesco Usai
 

Viewers also liked (7)

PPT
Buildstore Pres Lorraine
spikeytrim
 
PDF
Onnivori vegetariani vegani il dibattito è aperto 19 aprile 2012
bomber87
 
PDF
Mangiare bene fa male e 21 marzo 2012 light
bomber87
 
PDF
Dove Evolution
Fawio
 
PDF
Blogger2008
Fawio
 
PPT
Subversive talk - Eclipse Summit Europe 2008
guestee71f
 
PPT
Metsloomad
Elna Pähn
 
Buildstore Pres Lorraine
spikeytrim
 
Onnivori vegetariani vegani il dibattito è aperto 19 aprile 2012
bomber87
 
Mangiare bene fa male e 21 marzo 2012 light
bomber87
 
Dove Evolution
Fawio
 
Blogger2008
Fawio
 
Subversive talk - Eclipse Summit Europe 2008
guestee71f
 
Metsloomad
Elna Pähn
 
Ad

Similar to Scala coated JVM (20)

PDF
Scala for Java Programmers
Eric Pederson
 
ODP
Scala ntnu
Alf Kristian Støyle
 
PPTX
An introduction to scala
Xing
 
PDF
The Scala Programming Language
league
 
PDF
Workshop Scala
Bert Van Vreckem
 
ODP
Introduction To Scala
Basuk
 
PDF
Introduction To Scala
Innar Made
 
PDF
Introduction to Scala
Aleksandar Prokopec
 
PDF
A bit about Scala
Vladimir Parfinenko
 
PPT
Scala uma poderosa linguagem para a jvm
Isaias Barroso
 
PDF
Scala at GenevaJUG by Iulian Dragos
GenevaJUG
 
PPTX
Scala, Play 2.0 & Cloud Foundry
Pray Desai
 
PDF
Scala: Object-Oriented Meets Functional, by Iulian Dragos
3Pillar Global
 
PDF
Meet scala
Wojciech Pituła
 
PDF
BCS SPA 2010 - An Introduction to Scala for Java Developers
Miles Sabin
 
PDF
An Introduction to Scala for Java Developers
Miles Sabin
 
PDF
Getting Started With Scala
Meetu Maltiar
 
PDF
Getting Started With Scala
Xebia IT Architects
 
PDF
An Introduction to Scala (2014)
William Narmontas
 
PDF
A Brief Introduction to Scala for Java Developers
Miles Sabin
 
Scala for Java Programmers
Eric Pederson
 
An introduction to scala
Xing
 
The Scala Programming Language
league
 
Workshop Scala
Bert Van Vreckem
 
Introduction To Scala
Basuk
 
Introduction To Scala
Innar Made
 
Introduction to Scala
Aleksandar Prokopec
 
A bit about Scala
Vladimir Parfinenko
 
Scala uma poderosa linguagem para a jvm
Isaias Barroso
 
Scala at GenevaJUG by Iulian Dragos
GenevaJUG
 
Scala, Play 2.0 & Cloud Foundry
Pray Desai
 
Scala: Object-Oriented Meets Functional, by Iulian Dragos
3Pillar Global
 
Meet scala
Wojciech Pituła
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
Miles Sabin
 
An Introduction to Scala for Java Developers
Miles Sabin
 
Getting Started With Scala
Meetu Maltiar
 
Getting Started With Scala
Xebia IT Architects
 
An Introduction to Scala (2014)
William Narmontas
 
A Brief Introduction to Scala for Java Developers
Miles Sabin
 
Ad

Recently uploaded (20)

PDF
NewMind AI Weekly Chronicles – July’25, Week III
NewMind AI
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PPTX
The Future of AI & Machine Learning.pptx
pritsen4700
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PDF
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
PDF
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
PPTX
Agentic AI in Healthcare Driving the Next Wave of Digital Transformation
danielle hunter
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PDF
introduction to computer hardware and sofeware
chauhanshraddha2007
 
PDF
Brief History of Internet - Early Days of Internet
sutharharshit158
 
PPTX
AI Code Generation Risks (Ramkumar Dilli, CIO, Myridius)
Priyanka Aash
 
PPTX
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
PDF
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
PDF
TrustArc Webinar - Navigating Data Privacy in LATAM: Laws, Trends, and Compli...
TrustArc
 
PDF
Market Insight : ETH Dominance Returns
CIFDAQ
 
PPTX
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
PDF
Researching The Best Chat SDK Providers in 2025
Ray Fields
 
PDF
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
NewMind AI Weekly Chronicles – July’25, Week III
NewMind AI
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
The Future of AI & Machine Learning.pptx
pritsen4700
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
Agentic AI in Healthcare Driving the Next Wave of Digital Transformation
danielle hunter
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
introduction to computer hardware and sofeware
chauhanshraddha2007
 
Brief History of Internet - Early Days of Internet
sutharharshit158
 
AI Code Generation Risks (Ramkumar Dilli, CIO, Myridius)
Priyanka Aash
 
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
TrustArc Webinar - Navigating Data Privacy in LATAM: Laws, Trends, and Compli...
TrustArc
 
Market Insight : ETH Dominance Returns
CIFDAQ
 
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
Researching The Best Chat SDK Providers in 2025
Ray Fields
 
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 

Scala coated JVM

  • 1. Scala coated JVM @ Joint meeting of Java User Group Scotland and Scala Scotland Stuart Roebuck [email protected]
  • 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) = "[email protected]" name: String = stuart.roebuck address: String = proinnovate.com
  • 20. Demo 3 Building a Scala project with sbt
  • 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/