This document provides an introduction to the Scala programming language. It outlines an agenda that covers what Scala is, its history, implementations, benefits, and basics. Key topics include classes and objects, functional programming, traits and mixins, and integrating Scala and Java. The goal is to help attendees understand Scala, be interested in learning more, and get started installing Scala.
2. Agenda …
The four W’s plus an H
• What: Scala Intro
• When: Scala History
• Who: Scala Implementations
• Why: A Case for Scala
• How: The Basics of Scala
– Getting Up and Running
– Classes and Objects
– Functional Programming
– Traits and Mixins
– Java in Scala
– Scala in Java
An Introduction to Scala
March 7, 2012 2
3. Agenda …
Goals
• Have an understanding of what Scala is
• Have an interest in learning more
• Go install Scala!
An Introduction to Scala
March 7, 2012 3
4. What: Scala Intro …
What is Scala?
Scala is a general purpose programming language designed to express common programming
patterns in a concise, elegant and type-safe way. It smoothly integrates features of object-
oriented and functional languages, enabling Java and other programmers to be more
productive. Code sizes are typically reduced by a factor of two to three when compared to an
equivalent Java application.
• Origin of name is two-fold
– Scala is Italian for staircase. Scala is considered a “step up” from other languages
– SCAlableLanguage
• Seamless integration with Java. Runs in the JVM
• Proven performer in high transaction, highly scalable environments
• Developers can follow an imperative or functional style
• ThoughtWorks has put Scala in the “trial” radar category (July 2011)
An Introduction to Scala
March 7, 2012 4
5. When: Scala History …
Scala History … 1995 to 2012
Brief history of Scala
• Developed by Martin Odersky
– 1995 he learned of Java and wrote functional language that compiled to Java bytecode - Pizza
– Pizza evolved into what we now recognize as Java generics
• Sun approached Odersky in 1997 to write Java 1.1 compiler
• Odersky led javac development from Java 1.1 through 1.4
• In 1999, Odersky joined EPFL to conduct research into improving functional and OO languages
• Design of Scala began in 2001 and first release was in 2003
• Early releases of compiler written in Java
• Version 2.0.0 introduced a completely rewritten compiler in Scala
• Current version 2.9.1 released in August 2011
An Introduction to Scala
March 7, 2012 5
6. Who: Scala Implementations …
Scala is finding a home in high transaction environments
• Twitter Kestrel – Twitter’s message queue server
– Ported from RoR
• FourSquare – Message queue, website, mobile
website and RESTful API
• LinkedIn – Public and backend RESTful API’s
– Ported from RoR
• Novell – Pulse, a cloud-based, real-time
collaboration platform for the enterprise
An Introduction to Scala
March 7, 2012 6
7. Why: A Case for Scala …
Is Scala a fit?
Upside of Scala
• Ease of integration with existing Java environments
• When a functional style is utilized, scales easily
• Performance is equivalent, and in some cases, better than Java
• Good candidate for medium risk greenfield projects
• Learning curve is not massive, as Scala follows Java syntax
Downside of Scala
• Toolset is immature
– IDE integration is weak, but improving
– Java profiling tools can be used, but difficult
• Overcoming Java footprint will be difficult. It’s comfortable and works. It’s the COBOL/C+ of our
generation
• User acceptance still low due to lack of knowledge and reasons listed above
An Introduction to Scala
March 7, 2012 7
8. How: The Basics of Scala...
What you need to know to get started!
• Getting Up and Running
• Building Blocks
• Classes and Objects
• Functional Programming
• Traits and Mixins
• Java in Scala
• Scala in Java
An Introduction to Scala
March 7, 2012 8
9. How: The Basics of Scala …
Getting up and running
Required
• Java 1.5 or greater
• Scala 2.9.1 distribution
Optional
• SBT – Simple Build Tool
• IDE Plugin
– ScalaIDE (Eclipse – must use Helios)
– Scala Plugin for IntelliJ IDEA
– Scala Plugin for NetBeans
Notes:
1) Installation of Scala and SBT involve expanding compressed file and adding to PATH
2) IDE installation varies by tool; some dependency on IDE release number
3) ScalaIDE officially supported by Typesafe
An Introduction to Scala
March 7, 2012 9
10. How: The Basics of Scala …
Building Blocks
Declarations - var
• A var is similar to a non-final variable in Java
• If type is not declared, it will be inferred from the assigned object
• Once initialized, it can be reassigned (mutable), but type cannot change
• Object can be assigned at any time
Example
classVarA(n:Int) {
varvalue =n
}
classVarB(n:Int) {
valvalue =newVarA(n)
}
objectExampleVar {
varx=newVarB(5)
x=newVarB(6)
// x.value = new VarA(7)
x.value.value=7
}
An Introduction to Scala
March 7, 2012 10
11. How: The Basics of Scala …
Building Blocks
Declarations - val
• A val is similar to a final variable in Java
• Once initialized, it can not be reassigned (immutable)
• Object must be initialized at declaration
• Object cannot be reassigned, but internal state can be modified
Example
classValA(n:Int) {
varvalue =n
}
classValB(n:Int) {
valvalue =newValA(n)
}
objectExampleVar {
valx=newValB(5)
x.value.value=6
}
An Introduction to Scala
March 7, 2012 11
12. How: The Basics of Scala …
Building Blocks
Declarations - def
• A defis used to define a function
• A comma-separated list of parameters in parentheses follows the name
• The type of the return value must be defined following the parameters
• If a return type is not included, you are defining a “procedure”
• The equals sign hints to the fact a function defines an expression resulting in a value
• The final value of the control block is the return value
Example
classExampleDef(n:Int, a:Int, b:Int) {
valvalue =n + max(a,b)
defmax(x:Int, y:Int):Int={
if(x>y) x
elsey
}
}
An Introduction to Scala
March 7, 2012 12
13. How: The Basics of Scala… Classes and Objects …
Classes
Class
• A class in Scala looks similar to a class in Java – minus the boilerplate code
• Public by default
• Getters and setters defined by variable declaration
Example
classCoordinate() {
vardegrees =0.0
varminutes =0.0
varseconds =0.0
defasDegrees=degrees + minutes/60.0+ seconds/60.0/60.0
defasRadians=asDegrees.toRadians
}
objectExample extendsApp {
vallatitude =newCoordinate
latitude.degrees=32.0
latitude.minutes=57.0
latitude.seconds=30.762
An Introduction to Scala
}
March 7, 2012 13
14. How: The Basics of Scala … Classes and Objects …
Classes
Class – Primary Constructor
• More concise
• val has getter only
• Primary constructor creates the fields
Example
classCoordinate(valdegrees:Double, valminutes:Double, valseconds:Double) {
defasDegrees=degrees + minutes/60.0+ seconds/60.0/60.0
defasRadians=asDegrees.toRadians
}
objectExample extendsApp {
vallatitude =newCoordinate(32.0, 57.0, 30.762)
vallongitude =newCoordinate(96.0, 49.0, 25.1076)
println(latitude.degrees) // prints 32.0
}
An Introduction to Scala
March 7, 2012 14
15. How: The Basics of Scala … Classes and Objects …
Classes
Class – Auxiliary Constructor
• Auxiliary constructor is created as a def this
• Must start with a call to a previously defined auxiliary or primary constructor
Example
classCoordinate(valdegrees:Double, valminutes:Double, valseconds:Double) {
defthis(degrees:Double, minutes:Double) =this(degrees, minutes, 0.0)
defthis(degrees:Double) =this(degrees, 0.0)
defthis() =this(0.0)
defasDegrees=degrees + minutes/60.0+ seconds/60.0/60.0
defasRadians=asDegrees.toRadians
}
objectExample extendsApp {
vallatitude =newCoordinate(32.0)
vallongitude =newCoordinate(96.0, 49.0)
println(latitude.minutes) // prints 0.0
println(longitude.minutes) // prints 49.0
}
An Introduction to Scala
March 7, 2012 15
16. How: The Basics of Scala… Classes and Objects …
Objects
Object
• Creates a singleton of a class
• Can be used as a home for miscellaneous functions
• No constructor parameters
Example
objectCrederaLatitudeextendsCoordinate {
this.degrees=32.0
this.minutes=57.0
this.seconds=30.762
defprintCoordinate=println(this.asDegrees)
}
classCoordinate(valdegrees:Double, valminutes:Double, valseconds:Double) {
defthis(degrees:Double, minutes:Double) =this(degrees, minutes, 0.0)
defthis(degrees:Double) =this(degrees, 0.0)
defthis() =this(0.0)
defasDegrees=degrees + minutes/60.0+ seconds/60.0/60.0
defasRadians=asDegrees.toRadians
}
objectExample extendsApp {
CrederaLatitude.printCoordinate// prints 32.958545
}
An Introduction to Scala
March 7, 2012 16
17. How: The Basics of Scala … Functional Programming …
Functional programming… defined
Definition
• Treats computations as the evaluation of mathematical functions
• Avoids state and mutable data
• Calling a function twice, with the same arguments, should produce the same results both times
• First-class functions are functions that either take other functions as arguments or return them as
results
• In Scala, a function literal (the definition) is compiled to a functional value (a class)
• Functional values can be assigned to a val or var. If assigned to a var, it is mutable.
Example
varincrease =(x:Int) =>x + 1
valresult0=increase(10) // results in 11
An Introduction to Scala
March 7, 2012 17
18. How: The Basics of Scala … Functional Programming …
Functional programming… defined
Definition
• Treats computations as the evaluation of mathematical functions
• Avoids state and mutable data
• Calling a function twice, with the same arguments, should produce the same results both times
• First-class functions are functions that either take other functions as arguments or return them as
results
• In Scala, a function literal (the definition) is compiled to a functional value (a class)
• Functional values can be assigned to a val or var. If assigned to a var, it is mutable.
Example
varincrease =(x:Int) =>x + 1
valresult0=increase(10) // results in 11
increase =(x:Int) =>x + 10
valresult1=increase(10) //results in 20
An Introduction to Scala
March 7, 2012 18
19. How: The Basics of Scala … Functional Programming …
Passing functional values
Passing as a value
• Functional values can be passed as a value into another function
• Common use is to make calls on the immutable collection List
Example
valsomeNumbers=List(-22,-19,-12,-9,-2,0,1,5,9,32)
valprintList=(x:Int) =>println(x)
println("print all numbers: ")
someNumbers.foreach(printList)
println("-----------------------------------")
An Introduction to Scala
March 7, 2012 19
20. How: The Basics of Scala … Functional Programming …
Passing functional values
Passing as a value
• Functional values can be passed as a value into another function
• Common use is to make calls on the immutable collection List
Example
valsomeNumbers=List(-22,-19,-12,-9,-2,0,1,5,9,32)
valprintList=(x:Int) =>println(x)
println("print all numbers: ")
someNumbers.foreach(printList)
println("-----------------------------------")
println("print only positive numbers:")
valfilterList=(x:Int) =>x>0
someNumbers.filter(filterList).foreach(printList)
An Introduction to Scala
March 7, 2012 20
21. How: The Basics of Scala … Traits and Mixins …
Traits and Mixins
Trait
• Scala developers saw inherent problems with Java interfaces
• Scala solution is a combination of Java interfaces and Ruby mixins called traits
• Like an object, traits do not have constructors
• Added to class via the extends keyword
• Additional traits can be “mixed in” via the with keyword
An Introduction to Scala
March 7, 2012 21
22. How: The Basics of Scala … Java in Scala …
Integration
Java in Scala importorg.joda.time._
• Add jar to your CLASSPATH
traitCurrentTime {
• Import package or class valnow =newDateTime()
• Implement an object using the class }
An Introduction to Scala
March 7, 2012 22
23. How: The Basics of Scala … Java in Scala… Scala in Java …
Integration
Java in Scala importorg.joda.time._
• Add jar to your CLASSPATH
traitCurrentTime {
• Import package or class valnow =newDateTime()
• Implement an object using the class }
Scala in Java
importcom.credera.tech.scala.*;
• Compile to a jar
• Add jar to your CLASSPATH public classHello {
public static void main(String[] args) {
• Import package or class
System.out.println("Hello, this is java.");
• Implement an object using the class CrederaOffice.printOfficeLocation();
}
}
An Introduction to Scala
March 7, 2012 23
24. Appendix … Web References ...
Resources
Web Resources
Description Link
Scala http://www.scala-lang.org
SBT – Simple Build Tool http://github.com/harrah/xsbt
ScalaIDE for Eclipse http://scala-ide.org
Scala Plugin for IntelliJ IDEA http://confluence.jetbrains.net/display/SCA/Scala_Plugin+for+IntelliJ+IDEA
Scala Plugin for NetBeans http://wiki.netbeans.org/Scala
ThoughtWorks Technology Radar http://thoughtworks.com/radar
Indeed.com Scala Job Trends http://indeed.com/jobtrends?q=scala&l=&relative=1
Twitter’s Scala Experience http://web2expo.com/webexsf2009/public/schedule/detail/6110
LinkedIn’s Scala Experience http://infoq.com/articles/linkedin-scala-jruby/voldement
Java Interfaces Discussion http://www.codecommit.com/blog/scala/scala-for-java-refugees-part-5
An Introduction to Scala
March 7, 2012 24
25. Contact ...
Contact Me!
blemons@credera.com
@brentlemons
slideshare.net/brentlemons
An Introduction to Scala
March 7, 2012 25
Notas do Editor
Trial category indicates: “worth pursuing. It is important to understand how to build up this capability. Enterprises should try this technology on a project that can handle the risk.”“”wider applicability of Scala makes it more approachable for enterprise developers, and we have witnessed great successes in the adoption of Scala.”
Think of sbt as being similar to maven or antShow ide and run HowdyBasic
Field
FieldGo to ide, show ExampleValShow effects of trying to reassign a val
method
Class is a blueprint for an object. Class contains fields and methods.
Class is a blueprint for an object. Class contains fields and methods.
Class is a blueprint for an object. Class contains fields and methods.
Class is a blueprint for an object. Class contains fields and methods.
Imperative programming can have side effect – the changing of program stateImportance of no state and mutable data comes into play with multi threaded applicationsAdditionally, if there is no state, system can easily be scaled horizontally – see twitter, linkedin, etcHas add on slide
Imperative programming can have side effect – the changing of program stateImportance of no state and mutable data comes into play with multi threaded applicationsAdditionally, if there is no state, system can easily be scaled horizontally – see twitter, linkedin, etcDemonstrate with Tester
Imperative programming can have side effect – the changing of program stateHas add on slide
Imperative programming can have side effect – the changing of program stateDemonstrate with ListTester
Go to ideStart demonstration from Coordinate or GeoLocation
Go to ide. Show addingjoda to classpathHas add on slide
Go to ide. Show addingjoda to classpathGo to ide. Show adding scala to java classpathRun Hello.java