SlideShare a Scribd company logo
1 of 50
Download to read offline
Scala
Simplifying Development
ScalaDay Italy
Milan, May 25, 2013
Mirco Dotta
Saturday, May 25, 13
Is Scala the Java of the
future?
Saturday, May 25, 13
• It has basically everything Java has now
• It has closures (planned for Java 8)
• It has rich interfaces (Java 8 defender
methods), and more
• It is completely interoperable and runs
about as fast as Java
Saturday, May 25, 13
How is Scala different
from Java?
Saturday, May 25, 13
Concise Syntax
Saturday, May 25, 13
public class Time {
private final int hours;
private final int minutes;
public Time(int hours, int minutes) {
this.hours = hours;
this.minutes = minutes;
}
public int getHours() { return hours; }
public int getMinutes() { return minutes; }
}
class Time(val hours: Int, val minutes: Int)
Saturday, May 25, 13
Statically typed
but feels dynamic
Saturday, May 25, 13
val x = 2
type is inferred
no semicolon
Saturday, May 25, 13
Unifies OOP and FP
Saturday, May 25, 13
Every value is an object
Saturday, May 25, 13
List(1,2,3).filter(x => x > 2) //> res: List[Int] = List(3)
Anonymous function Int => Boolean
List(1, 2, 3).filter(
new Function[Int, Boolean] {
def apply(x: Int): Boolean = x > 2
}
)
/
//> res: List[Int] = List(3)
Functions are “just” objects
Saturday, May 25, 13
Everything is an
expression
Saturday, May 25, 13
def max(x: Int, y: Int): Int =
if (x > y) x else y
no return statement
val x: Int = {
val y = 10
val z = 5
y + z
}
blocks evaluate to last
expression
Saturday, May 25, 13
Every operation is a
method call
Saturday, May 25, 13
val x: Int = 10
val y = x + 10
same as x.+(10)
Saturday, May 25, 13
Principles, not Rules
Saturday, May 25, 13
Users can write their own operators
Principle
Saturday, May 25, 13
class Complex(val re: Int, val im: Int = 0) {
def +(that: Complex) =
new Complex(this.re + that.re, this.im + that.im)
override def toString = s"$re + $im"
}
val c1 = new Complex(1, 2) //> c1 : Complex = 1 + 2
val c2 = new Complex(2, 2) //> c2 : Complex = 2 + 2
val c = c1 + c2 //> c : Complex = 3 + 4
default argument
Saturday, May 25, 13
• new types can look like built-in ones
• “grow the language”
Saturday, May 25, 13
Powerful collections
Saturday, May 25, 13
case class Time(hours: Int, minutes: Int = 0)
val times = List(Time(1), Time(2), Time(12,30), Time(16,15))
times.filter(time => time.hours >= 12)
//> res: List[Time] = List(Time(12,30), Time(16,15))
times.map(time => Time(time.hours + 1, time.minutes))
//> res: List[Time] = List(Time(2,0), Time(3,0), Time(13,30),
Time(17,15))
times.take(2) //> res: List[Time] = List(Time(1,0), Time(2,0))
times.groupBy(time => time.minutes) //> res: Map[Int,List[Time]] =
Map(30 -> List(Time(12,30)), 15 -> List(Time(16,15)), 0 ->
List(Time(1,0), Time(2,0)))
times.head //> res: Time = Time(1,0)
times.last //> res: Time = Time(16,15)
Saturday, May 25, 13
For-comprehension
Saturday, May 25, 13
• More general than for-loops
• Used to iterate, filter, and generate new
collections
Saturday, May 25, 13
for (p <- persons; pr <- p.projects;
if pr.overdue) yield p.name
may have any number of generators
guard construct a new collection of the same
type, element by element
p is in scope for other generators
Saturday, May 25, 13
times.filter(time => time.hours >= 12)
//> res: List[Time] = List(Time(12,30), Time(16,15))
for(time <- times;
if time.hours >= 12) yield time
//>res: List[Time] = List(Time(12,30), Time(16,15))
times.map(time => Time(time.hours + 1, time.minutes))
//> res: List[Time] = List(Time(2,0), Time(3,0), Time(13,30),
Time(17,15))
for(time <- times)
yield Time(time.hours + 1, time.minutes)
//> res: List[Time] = List(Time(2,0), Time(3,0), Time(13,30),
Time(17,15))
Saturday, May 25, 13
Desugared to calls to filter, map, and
flatMap
Saturday, May 25, 13
Readily available on any class
implementing those methods!
Saturday, May 25, 13
Traits
Saturday, May 25, 13
• Like Java interfaces, but traits
• can have behavior (like Java 8 interfaces
with defender methods)
• can have state
• enable multiple inheritance
Saturday, May 25, 13
public interface Comparable<T> {
int compareTo(int o);
}
trait Comparable[T] {
def compareTo(that: T): Int
}
def <(that: T): Boolean =
(this compare that) < 0
def >(that: T): Boolean =
(this compare that) > 0
//... Rich
Interface
Saturday, May 25, 13
Multiple Inheritance
• Traits can mix-in multiple traits
• Classes can mix-in multiple traits
• Both Class and Trait can inherit at most
from one Class
Saturday, May 25, 13
trait Bird {
def fly: String = "I'm flying!"
}
trait Swimmer {
def swim: String = "I'm swimming!"
}
class Fish extends Swimmer
class Duck extends Bird with Swimmer
Saturday, May 25, 13
Embedding DSLs
Saturday, May 25, 13
val c = new Complex(1, 2) //> c : Complex = 1 + 2
Sum Complex & Int
How could we do it?
val c1 = 1 + c //> ???
val c1 = c + 1 //> ???
Saturday, May 25, 13
val c1 = 1 + c //> ???
• This doesn’t compile because the type of c
is not conform to the type expected by the
+ method
• In Java there would simply be no way to
make this work
Saturday, May 25, 13
Implicit Conversions
Saturday, May 25, 13
• When there is a type error, the compiler
looks for an implicit that could heal the
expression
• You are already used to the idea of types
being automatically converted into others
• E.g.,Type coercion in Java!
int a = 2;
double b = a;
int is converted into a
double
Saturday, May 25, 13
Scala gives you the power of creating
your own conversions
Saturday, May 25, 13
class RichInt(n: Int) {
def +(other: Complex) =
new Complex(n) + other
}
Let’s create a class that can sum Int with Complex
val c = new Complex(1, 2) //> c : Complex = 1 + 2
val c1 = RichInt(1) + c //> c1 : Complex = 2 + 2
Saturday, May 25, 13
But, we want to write
val c1 = 1 + c
And not
val c1 = RichInt(1) + c
Saturday, May 25, 13
Implicit conversion!
Saturday, May 25, 13
implicit def int2richInt(n: Int) = new RichInt(n)
val c = new Complex(1, 2) //> c : Complex = 1 + 2
val c1 = 1 + c //> c1 : Complex = 2 + 2
And the compiler will take care of applying the
conversion
val c1 = int2richInt(1) + c
Saturday, May 25, 13
Scala simplifies
development because...
Saturday, May 25, 13
Less is More
Saturday, May 25, 13
Few language
constructs with high
abstraction power
Saturday, May 25, 13
It’s Fun!
Saturday, May 25, 13
Good for your
business?
Saturday, May 25, 13
Saturday, May 25, 13
Get Started in 5’
http://www.typesafe.com/platform/getstarted
Saturday, May 25, 13
Thanks
twitter: @mircodotta
Saturday, May 25, 13

More Related Content

What's hot

CodeFest 2014. Axel Rauschmayer — JavaScript’s variables: scopes, environment...
CodeFest 2014. Axel Rauschmayer — JavaScript’s variables: scopes, environment...CodeFest 2014. Axel Rauschmayer — JavaScript’s variables: scopes, environment...
CodeFest 2014. Axel Rauschmayer — JavaScript’s variables: scopes, environment...
CodeFest
 

What's hot (20)

Scilab
Scilab Scilab
Scilab
 
Standard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingStandard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented Programming
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
Brief tour of psp-std
Brief tour of psp-stdBrief tour of psp-std
Brief tour of psp-std
 
Python - Lecture 10
Python - Lecture 10Python - Lecture 10
Python - Lecture 10
 
CodeFest 2014. Axel Rauschmayer — JavaScript’s variables: scopes, environment...
CodeFest 2014. Axel Rauschmayer — JavaScript’s variables: scopes, environment...CodeFest 2014. Axel Rauschmayer — JavaScript’s variables: scopes, environment...
CodeFest 2014. Axel Rauschmayer — JavaScript’s variables: scopes, environment...
 
Applied numerical methods lec2
Applied numerical methods lec2Applied numerical methods lec2
Applied numerical methods lec2
 
Java patterns in Scala
Java patterns in ScalaJava patterns in Scala
Java patterns in Scala
 
Clojure
ClojureClojure
Clojure
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that Letter
 
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
 
Refactoring to Immutability
Refactoring to ImmutabilityRefactoring to Immutability
Refactoring to Immutability
 
Yin Yangs of Software Development
Yin Yangs of Software DevelopmentYin Yangs of Software Development
Yin Yangs of Software Development
 
Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012
 
Introducing: A Complete Algebra of Data
Introducing: A Complete Algebra of DataIntroducing: A Complete Algebra of Data
Introducing: A Complete Algebra of Data
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
 
Heaps & Adaptable priority Queues
Heaps & Adaptable priority QueuesHeaps & Adaptable priority Queues
Heaps & Adaptable priority Queues
 
Algorithm analysis basics - Seven Functions/Big-Oh/Omega/Theta
Algorithm analysis basics - Seven Functions/Big-Oh/Omega/ThetaAlgorithm analysis basics - Seven Functions/Big-Oh/Omega/Theta
Algorithm analysis basics - Seven Functions/Big-Oh/Omega/Theta
 
U3.stack queue
U3.stack queueU3.stack queue
U3.stack queue
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
 

Viewers also liked

Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)
mircodotta
 
Planificacion ingles i
Planificacion ingles iPlanificacion ingles i
Planificacion ingles i
AMELIA3050
 
Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)
mircodotta
 
Planificacion ingles ii
Planificacion ingles iiPlanificacion ingles ii
Planificacion ingles ii
AMELIA3050
 

Viewers also liked (16)

Synthesis responses document en
Synthesis responses document enSynthesis responses document en
Synthesis responses document en
 
Managing Binary Compatibility in Scala (Scala Days 2011)
Managing Binary Compatibility in Scala (Scala Days 2011)Managing Binary Compatibility in Scala (Scala Days 2011)
Managing Binary Compatibility in Scala (Scala Days 2011)
 
HyProCure Before & After
HyProCure Before & AfterHyProCure Before & After
HyProCure Before & After
 
Managing Binary Compatibility in Scala (Scala Lift Off 2011)
Managing Binary Compatibility in Scala (Scala Lift Off 2011)Managing Binary Compatibility in Scala (Scala Lift Off 2011)
Managing Binary Compatibility in Scala (Scala Lift Off 2011)
 
Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)
 
Elvis orientation
Elvis orientationElvis orientation
Elvis orientation
 
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems (Soft-Sha...
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems (Soft-Sha...Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems (Soft-Sha...
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems (Soft-Sha...
 
Akka streams
Akka streamsAkka streams
Akka streams
 
Scala Past, Present & Future
Scala Past, Present & FutureScala Past, Present & Future
Scala Past, Present & Future
 
Lightbend Lagom: Microservices Just Right (Scala Days 2016 Berlin)
Lightbend Lagom: Microservices Just Right (Scala Days 2016 Berlin)Lightbend Lagom: Microservices Just Right (Scala Days 2016 Berlin)
Lightbend Lagom: Microservices Just Right (Scala Days 2016 Berlin)
 
Planificacion ingles i
Planificacion ingles iPlanificacion ingles i
Planificacion ingles i
 
Akka streams scala italy2015
Akka streams scala italy2015Akka streams scala italy2015
Akka streams scala italy2015
 
Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)
 
Lightbend Lagom: Microservices Just Right
Lightbend Lagom: Microservices Just RightLightbend Lagom: Microservices Just Right
Lightbend Lagom: Microservices Just Right
 
Planificacion
PlanificacionPlanificacion
Planificacion
 
Planificacion ingles ii
Planificacion ingles iiPlanificacion ingles ii
Planificacion ingles ii
 

Similar to Scala: Simplifying Development

scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
Distributed Data Structures
Distributed Data StructuresDistributed Data Structures
Distributed Data Structures
PDX Web & Design
 

Similar to Scala: Simplifying Development (20)

Learn basics of Clojure/script and Reagent
Learn basics of Clojure/script and ReagentLearn basics of Clojure/script and Reagent
Learn basics of Clojure/script and Reagent
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala Makeover
 
Kotlin boost yourproductivity
Kotlin boost yourproductivityKotlin boost yourproductivity
Kotlin boost yourproductivity
 
JavaOne 2013 - Clojure for Java Developers
JavaOne 2013 - Clojure for Java DevelopersJavaOne 2013 - Clojure for Java Developers
JavaOne 2013 - Clojure for Java Developers
 
scala.reflect, Eugene Burmako
scala.reflect, Eugene Burmakoscala.reflect, Eugene Burmako
scala.reflect, Eugene Burmako
 
Евгений Бурмако «scala.reflect»
Евгений Бурмако «scala.reflect»Евгений Бурмако «scala.reflect»
Евгений Бурмако «scala.reflect»
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Programación funcional con haskell
Programación funcional con haskellProgramación funcional con haskell
Programación funcional con haskell
 
Speaking Scala: Refactoring for Fun and Profit (Workshop)
Speaking Scala: Refactoring for Fun and Profit (Workshop)Speaking Scala: Refactoring for Fun and Profit (Workshop)
Speaking Scala: Refactoring for Fun and Profit (Workshop)
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
 
Functional Programming - Past, Present and Future
Functional Programming - Past, Present and FutureFunctional Programming - Past, Present and Future
Functional Programming - Past, Present and Future
 
Functional Programming Past Present Future
Functional Programming Past Present FutureFunctional Programming Past Present Future
Functional Programming Past Present Future
 
Sequence and Traverse - Part 2
Sequence and Traverse - Part 2Sequence and Traverse - Part 2
Sequence and Traverse - Part 2
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
 
Functional Programming in Scala: Notes
Functional Programming in Scala: NotesFunctional Programming in Scala: Notes
Functional Programming in Scala: Notes
 
Distributed Data Structures
Distributed Data StructuresDistributed Data Structures
Distributed Data Structures
 
Scalable JavaScript
Scalable JavaScriptScalable JavaScript
Scalable JavaScript
 

Recently uploaded

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
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)

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
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
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
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
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
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
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
 
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
 
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
 
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
 
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
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
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...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 

Scala: Simplifying Development

  • 1. Scala Simplifying Development ScalaDay Italy Milan, May 25, 2013 Mirco Dotta Saturday, May 25, 13
  • 2. Is Scala the Java of the future? Saturday, May 25, 13
  • 3. • It has basically everything Java has now • It has closures (planned for Java 8) • It has rich interfaces (Java 8 defender methods), and more • It is completely interoperable and runs about as fast as Java Saturday, May 25, 13
  • 4. How is Scala different from Java? Saturday, May 25, 13
  • 6. public class Time { private final int hours; private final int minutes; public Time(int hours, int minutes) { this.hours = hours; this.minutes = minutes; } public int getHours() { return hours; } public int getMinutes() { return minutes; } } class Time(val hours: Int, val minutes: Int) Saturday, May 25, 13
  • 7. Statically typed but feels dynamic Saturday, May 25, 13
  • 8. val x = 2 type is inferred no semicolon Saturday, May 25, 13
  • 9. Unifies OOP and FP Saturday, May 25, 13
  • 10. Every value is an object Saturday, May 25, 13
  • 11. List(1,2,3).filter(x => x > 2) //> res: List[Int] = List(3) Anonymous function Int => Boolean List(1, 2, 3).filter( new Function[Int, Boolean] { def apply(x: Int): Boolean = x > 2 } ) / //> res: List[Int] = List(3) Functions are “just” objects Saturday, May 25, 13
  • 13. def max(x: Int, y: Int): Int = if (x > y) x else y no return statement val x: Int = { val y = 10 val z = 5 y + z } blocks evaluate to last expression Saturday, May 25, 13
  • 14. Every operation is a method call Saturday, May 25, 13
  • 15. val x: Int = 10 val y = x + 10 same as x.+(10) Saturday, May 25, 13
  • 17. Users can write their own operators Principle Saturday, May 25, 13
  • 18. class Complex(val re: Int, val im: Int = 0) { def +(that: Complex) = new Complex(this.re + that.re, this.im + that.im) override def toString = s"$re + $im" } val c1 = new Complex(1, 2) //> c1 : Complex = 1 + 2 val c2 = new Complex(2, 2) //> c2 : Complex = 2 + 2 val c = c1 + c2 //> c : Complex = 3 + 4 default argument Saturday, May 25, 13
  • 19. • new types can look like built-in ones • “grow the language” Saturday, May 25, 13
  • 21. case class Time(hours: Int, minutes: Int = 0) val times = List(Time(1), Time(2), Time(12,30), Time(16,15)) times.filter(time => time.hours >= 12) //> res: List[Time] = List(Time(12,30), Time(16,15)) times.map(time => Time(time.hours + 1, time.minutes)) //> res: List[Time] = List(Time(2,0), Time(3,0), Time(13,30), Time(17,15)) times.take(2) //> res: List[Time] = List(Time(1,0), Time(2,0)) times.groupBy(time => time.minutes) //> res: Map[Int,List[Time]] = Map(30 -> List(Time(12,30)), 15 -> List(Time(16,15)), 0 -> List(Time(1,0), Time(2,0))) times.head //> res: Time = Time(1,0) times.last //> res: Time = Time(16,15) Saturday, May 25, 13
  • 23. • More general than for-loops • Used to iterate, filter, and generate new collections Saturday, May 25, 13
  • 24. for (p <- persons; pr <- p.projects; if pr.overdue) yield p.name may have any number of generators guard construct a new collection of the same type, element by element p is in scope for other generators Saturday, May 25, 13
  • 25. times.filter(time => time.hours >= 12) //> res: List[Time] = List(Time(12,30), Time(16,15)) for(time <- times; if time.hours >= 12) yield time //>res: List[Time] = List(Time(12,30), Time(16,15)) times.map(time => Time(time.hours + 1, time.minutes)) //> res: List[Time] = List(Time(2,0), Time(3,0), Time(13,30), Time(17,15)) for(time <- times) yield Time(time.hours + 1, time.minutes) //> res: List[Time] = List(Time(2,0), Time(3,0), Time(13,30), Time(17,15)) Saturday, May 25, 13
  • 26. Desugared to calls to filter, map, and flatMap Saturday, May 25, 13
  • 27. Readily available on any class implementing those methods! Saturday, May 25, 13
  • 29. • Like Java interfaces, but traits • can have behavior (like Java 8 interfaces with defender methods) • can have state • enable multiple inheritance Saturday, May 25, 13
  • 30. public interface Comparable<T> { int compareTo(int o); } trait Comparable[T] { def compareTo(that: T): Int } def <(that: T): Boolean = (this compare that) < 0 def >(that: T): Boolean = (this compare that) > 0 //... Rich Interface Saturday, May 25, 13
  • 31. Multiple Inheritance • Traits can mix-in multiple traits • Classes can mix-in multiple traits • Both Class and Trait can inherit at most from one Class Saturday, May 25, 13
  • 32. trait Bird { def fly: String = "I'm flying!" } trait Swimmer { def swim: String = "I'm swimming!" } class Fish extends Swimmer class Duck extends Bird with Swimmer Saturday, May 25, 13
  • 34. val c = new Complex(1, 2) //> c : Complex = 1 + 2 Sum Complex & Int How could we do it? val c1 = 1 + c //> ??? val c1 = c + 1 //> ??? Saturday, May 25, 13
  • 35. val c1 = 1 + c //> ??? • This doesn’t compile because the type of c is not conform to the type expected by the + method • In Java there would simply be no way to make this work Saturday, May 25, 13
  • 37. • When there is a type error, the compiler looks for an implicit that could heal the expression • You are already used to the idea of types being automatically converted into others • E.g.,Type coercion in Java! int a = 2; double b = a; int is converted into a double Saturday, May 25, 13
  • 38. Scala gives you the power of creating your own conversions Saturday, May 25, 13
  • 39. class RichInt(n: Int) { def +(other: Complex) = new Complex(n) + other } Let’s create a class that can sum Int with Complex val c = new Complex(1, 2) //> c : Complex = 1 + 2 val c1 = RichInt(1) + c //> c1 : Complex = 2 + 2 Saturday, May 25, 13
  • 40. But, we want to write val c1 = 1 + c And not val c1 = RichInt(1) + c Saturday, May 25, 13
  • 42. implicit def int2richInt(n: Int) = new RichInt(n) val c = new Complex(1, 2) //> c : Complex = 1 + 2 val c1 = 1 + c //> c1 : Complex = 2 + 2 And the compiler will take care of applying the conversion val c1 = int2richInt(1) + c Saturday, May 25, 13
  • 45. Few language constructs with high abstraction power Saturday, May 25, 13
  • 49. Get Started in 5’ http://www.typesafe.com/platform/getstarted Saturday, May 25, 13