2. Scala
Functional programming for the imperative mind
‘of the nature of or
expressing a
command;
commanding.’
- imperative. (n.d.).
Dictionary.com
3. Scala
‘imperative
Functional programmingisfor the imperative mind
programming a
programming paradigm
that describes
computation in terms of
statements that change
a program state.’
- Imperative programming
Wikipedia.com
6. What is Scala?
A programming language ...
• Runs on JVM (and .Net)
• Statically typed
• Object Oriented
• Functional
• From scripting to enterprise apps
7. Scalable language
• Scalable language constructs:
• Composition ‘in the small’
• Composition ‘in the large’
• Java interoperability
• Performance on par with Java
8. Scalable language
• Scalable language constructs:
• Composition ‘in the small’
• Composition ‘in the large’
• Java interoperability
• Performance on par with Java
Fuses functional and object oriented paradigms
10. Functional programming
• Focus on functions, not state fx=x+1
• Functions are values vs.
• Recursion, not loops x=x+1
• Immutability (‘referential transparency’)
• Schools of thought:
pure and impure (‘pragmatic’)
11. Functional programming
• Focus on functions, not state fx=x+1
• Functions are values vs.
• Recursion, not loops x=x+1
• Immutability (‘referential transparency’)
• Schools of thought:
pure and impure (‘pragmatic’)
12. Functional programming
• Focus on functions, not state
• Functions are values f g x = g(x)
• Recursion, not loops
• Immutability (‘referential transparency’)
• Schools of thought:
pure and impure (‘pragmatic’)
13. Functional programming
• Focus on functions, not state f0=0
fx=
• Functions are values
f (x - 1)
vs.
• Recursion, not loops for(i=x; i>0
; i--) {
• Immutability (‘referential transparency’)x--; }
• Schools of thought:
pure and impure (‘pragmatic’)
14. Functional programming
• Focus on functions, not state
• Functions are values
• Recursion, not loops
• Immutability (‘referential transparency’)
• Schools of thought:
pure and impure (‘pragmatic’)
15. Functional programming
Why should I care about FP?
• Concurrency: FP ‘killer app’
• Higher order functions: expressiveness boost
• Type-system: when present, often superior
• It is coming to a language near you
(C#, Java 8?)
16. FP in Scala
• First-class functions: functions are objects
with pleasing syntax
• Immutability
• Algebraic data-types and pattern matching
• Parametric polymorphism (e.g. generics)
18. Scala is like Java...
(Generic) classes: class Foo[T], or:
class Foo[+T]
public class Foo<T>
Methods:
def m(s : String) : Unit = ..
public void m(String s) {..}
Bean properties: private Foo foo; Real properties:
getFoo() {..}, setFoo(..) {..} var foo: Foo
Fully interoperable with existing Java
Mature, large amount of proven libraries
code
Class/Interface distinction, single Abstract classes, traits (restricted
inheritance. multiple inheritance)
22. Pure object orientation
Every operation is a method call:
1+3 1.+(3)
Console.println(“hi”) Console println “hi”
23. Pure object orientation
Every operation is a method call:
1+3 1.+(3)
Console.println(“hi”) Console println “hi”
Since operators are methods,
operator overloading is trivial.
24. Pure object orientation
Every operation is a method call:
1+3 1.+(3)
Console.println(“hi”) Console println “hi”
25. Pure object orientation
Every operation is a method call:
1+3 1.+(3)
Console.println(“hi”) Console println “hi”
35. Functional objects
• Functions are first-class values
• Function literals:
(x: Int) => x * 2
val double = (x: Int) => x * 2
36. Functional objects
• Functions are first-class values
• Function literals:
(x: Int) => x * 2
val double = (x: Int) => x * 2
double(2) == 4
What is the type of double?
43. Passing functions
But we can do this with anonymous classes...
Well, sort of... but:
• You need explicit interfaces (no function types)
• Verbose
• Doesn’t scale (syntactically and semantically)
• No true closures:
44. Passing functions
But we can do this with anonymous classes...
Well, sort of... but:
• You need explicit interfaces (no function types)
• Verbose
• Doesn’t scale (syntactically and semantically)
• No true closures:
45. Traits
• Compare trait with abstract class
• No interfaces, but: completely abstract traits
• Can mixin multiple traits, statically and
dynamically
46. Traits as rich interfaces
Java interfaces have two consumers with
conflicting interests:
1) Implementors
2) Users
47. Traits as rich interfaces
Java interfaces have two consumers with
conflicting interests:
1) Implementors
2) Users
48. Traits as stackable
modifications
• Situation: IntQueue interface (abstract trait),
IntQueueImpl implementation
• We want to add logging and filtering to any
IntQueue implementation
49. Traits as stackable
modifications
• Situation: IntQueue interface (abstract trait),
IntQueueImpl implementation
• We want to add logging and filtering to any
IntQueue implementation
50. Traits as stackable
modifications
• Situation: IntQueue interface (abstract trait),
IntQueueImpl implementation
• We want to add logging and filtering to any
IntQueue implementation
59. Actors
• Message-based concurrency
• Actors exchange immutable messages
• Extract them by pattern matching
Looks like language feature, but is a library
60. Other library features
• Enums
• Map ‘syntax’
• Events
• Using ‘keyword’ (e.g. Java 7 ‘automatic
resource management.’)
• Virtually all other Project Coin proposals
61. Other library features
• Enums
• Map ‘syntax’
• Events
• Using ‘keyword’ (e.g. Java 7 ‘automatic
resource management.’)
• Virtually all other Project Coin proposals
62. Other library features
• Enums
• Map ‘syntax’
• Events
• Using ‘keyword’ (e.g. Java 7 ‘automatic
resource management.’)
• Virtually all other Project Coin proposals
63. Other library features
• Enums
• Map ‘syntax’
• Events
• Using ‘keyword’ (e.g. Java 7 ‘automatic
resource management.’)
• Virtually all other Project Coin proposals
Lesson: choose language core wisely,
all else will follow...
64. Lift webframework
In own words:
✓Seaside's highly granular sessions and security
✓Rails fast flash-to-bang
✓Django's quot;more than just CRUD is includedquot;
✓Wicket's designer-friendly templating style
• Heavy use of actors for async features
• Integrated O/R mapping (surprisingly little
boilerplate code)
66. Requirements
• Person entity with age
property
• Method to separate
minors and adults
• Input: List[Person]
• Output: list of minors,
list of adults
• One pass over input
67. Requirements
• Person entity with age
property
• Method to separate
minors and adults
• Input: List[Person]
• Output: list of minors,
list of adults
• One pass over input
69. Scala progression
• Current version: 2.7.4
• Version 2.8 beta coming up:
• Package objects
• Named and default parameters
• Many library improvements
70. Tool support
• Major IDEs (Eclipse,
IntelliJ, NetBeans)
supported
• Maven support
• Scaladoc
• SBaz package manager
74. Scala hitting mainstream?
Reports of first switchers
Twitter, SAP, LinkedIn, Sony Pictures
April 2009: top-30 of TIOBE index
Lots of books appearing
75. Scala hitting mainstream?
“If I were to pick a language today
other than Java, it would be Scala”
James Gosling,
‘Father of Java’
76. Scala hitting mainstream?
“If Java programmers want to use
features that aren't present in the
language, I think they're probably best
off using another language that targets
the JVM, such a Scala and Groovy.”
Joshua Bloch
Author of ‘Effective Java’
77. Pro’s and cons
• Complexity
• Java interoperability
• Java -> Scala
• Hides accidental
complexity harder than
Scala -> Java
• Expressiveness
• Type-system may
• Uniform, extensible be intimidating
language
78. Conclusion
• Scala feels like ‘cleaned up Java on stereoids’
• Small core (takes some time to see it as such)
provides broad options
• Type inference brings ‘dynamic language’ feel
• Adoptation growing because of:
• Java interoperability
• Growing discontent with Java
79. Conclusion
• Scala feels like ‘cleaned up Java on stereoids’
• Small core (takes some time to see it as such)
provides broad options
• Type inference brings ‘dynamic language’ feel
• Adoptation growing because of:
• Java interoperability
• Growing discontent with Java
Scala provides deep features, but at the
same time helps getting things done.
80. More
information
http://www.scala-lang.org
http://liftweb.net
Article Java Magazine 1/2009
Intro, gaan het hebben over Scala
Wellicht al eens gehoord over FP, lijkt groeiende interesse
wat is imperatief? Ook wel procedureel, met state, het is wat we in Java eigenlijk doen.
Intro, gaan het hebben over Scala
Wellicht al eens gehoord over FP, lijkt groeiende interesse
wat is imperatief? Ook wel procedureel, met state, het is wat we in Java eigenlijk doen.
Intro, gaan het hebben over Scala
Wellicht al eens gehoord over FP, lijkt groeiende interesse
wat is imperatief? Ook wel procedureel, met state, het is wat we in Java eigenlijk doen.
Odersky: co-designer generics, original author javac.
Wellicht had hier oracle logo moeten staan :)
*Voordelen JVM (enorm veel tijd in optimalisatie, platform agnostisch etc.), ook wat nadelen (niet echt ingericht op FP constructies).
* OO, maar dan ook puur, en met extra functionaliteit
* Scripting: REPL shell
Scala redelijk uniek in samenvoegen OO+FP
OCaml en F# zijn toch meer FP met een OO systeem er aan geplakt.
Recursie niet alleen in functies, ook in data (bomen, lijsten)
Recursie niet alleen in functies, ook in data (bomen, lijsten)
Recursie niet alleen in functies, ook in data (bomen, lijsten)
Recursie niet alleen in functies, ook in data (bomen, lijsten)
Recursie niet alleen in functies, ook in data (bomen, lijsten)
Recursie niet alleen in functies, ook in data (bomen, lijsten)
Recursie niet alleen in functies, ook in data (bomen, lijsten)
Recursie niet alleen in functies, ook in data (bomen, lijsten)
Recursie niet alleen in functies, ook in data (bomen, lijsten)
Recursie niet alleen in functies, ook in data (bomen, lijsten)
Recursie niet alleen in functies, ook in data (bomen, lijsten)
Nieuwe paradigma’s hebben killer-app nodig
OO had GUIs, bij FP concurrency?
Typesysteem: niet noodzakelijk voor FP, traditioneel wel focus
Zonder diep in te gaan, voor we features gaan bekijken, dit is hoe Scala FP bevat.
*default modifier is public
*Type after identifier, type Unit == void
*zowel Scala->Java als Java->Scala interop. Dus, elkaars classes instantieren overerven etc.
*Abstract class ipv interfaces
Extenden van Java class (extends ook voor interfaces)
Type Unit -> void in Java
hashCode -> hashCode() , haakjes weglaten.
Soort van autoboxing, maar beter
* + is methode naam, kan je zelf op een class implementeren
* Leestekens legale identifiers in Scala
* Operator notatie ook te gebruiken met ‘normale’ methode namen
* In Java discussie: operator overloadig BigInts (en wat voor matrix etc.)? Scala: just do it.
* + is methode naam, kan je zelf op een class implementeren
* Leestekens legale identifiers in Scala
* Operator notatie ook te gebruiken met ‘normale’ methode namen
* In Java discussie: operator overloadig BigInts (en wat voor matrix etc.)? Scala: just do it.
* + is methode naam, kan je zelf op een class implementeren
* Leestekens legale identifiers in Scala
* Operator notatie ook te gebruiken met ‘normale’ methode namen
* In Java discussie: operator overloadig BigInts (en wat voor matrix etc.)? Scala: just do it.
* + is methode naam, kan je zelf op een class implementeren
* Leestekens legale identifiers in Scala
* Operator notatie ook te gebruiken met ‘normale’ methode namen
* In Java discussie: operator overloadig BigInts (en wat voor matrix etc.)? Scala: just do it.
* + is methode naam, kan je zelf op een class implementeren
* Leestekens legale identifiers in Scala
* Operator notatie ook te gebruiken met ‘normale’ methode namen
* In Java discussie: operator overloadig BigInts (en wat voor matrix etc.)? Scala: just do it.
*Java statics niet echt OO. Scala: Classes->te instantieren, singleton objects->één instantie
*Zelfde naam: companions -> toegang tot private members
*haakjes mogen weg bij methode aanroep zonder params; puntkomma’s ook optioneel!
*main methode op object Main, entrypoint applicatie
* Vorige slide goed opgelet: geen return type!
* Zijn natuurlijk allemaal op ISKA over closures geweest, maar toch een opfrisser
* Java heeft Anon. classes -> beperkingen, verbose (interface nodig), daarom weinig gebruikt
* Zijn natuurlijk allemaal op ISKA over closures geweest, maar toch een opfrisser
* Java heeft Anon. classes -> beperkingen, verbose (interface nodig), daarom weinig gebruikt
* Zijn natuurlijk allemaal op ISKA over closures geweest, maar toch een opfrisser
* Java heeft Anon. classes -> beperkingen, verbose (interface nodig), daarom weinig gebruikt
* Zijn natuurlijk allemaal op ISKA over closures geweest, maar toch een opfrisser
* Java heeft Anon. classes -> beperkingen, verbose (interface nodig), daarom weinig gebruikt
* Function0 tot Function22 op deze manier beschikbaar
* Function0 tot Function22 op deze manier beschikbaar
* Function0 tot Function22 op deze manier beschikbaar
* Function0 tot Function22 op deze manier beschikbaar
* Function0 tot Function22 op deze manier beschikbaar
* Function0 tot Function22 op deze manier beschikbaar
* Function0 tot Function22 op deze manier beschikbaar
Scala gaat nog verder, zelf control structures maken (by-name params)
* First trait/class with extends, then 0 or more times with
* Traits can have any member: defs, abstract defs, fields traits can extend from each other
* Traits are used in this fashion a lot for the Scala collection libs
* abstract override: target of super not known at design-time!
* calls resolve right-to-left
* selftype annotation: type of this can assume type of class where trait is mixed in!
* abstract override: target of super not known at design-time!
* calls resolve right-to-left
* selftype annotation: type of this can assume type of class where trait is mixed in!
* abstract override: target of super not known at design-time!
* calls resolve right-to-left
* selftype annotation: type of this can assume type of class where trait is mixed in!
* geen new keyword nodig: case class is class + companion object met apply method!
* Sealed abstract class: compiler kan checken of alle cases gedekt zijn
* geen new keyword nodig: case class is class + companion object met apply method!
* Sealed abstract class: compiler kan checken of alle cases gedekt zijn
* geen new keyword nodig: case class is class + companion object met apply method!
* Sealed abstract class: compiler kan checken of alle cases gedekt zijn
* Twee doelen: selecteren goede case, en binden van variabelen in 1 stap
* Java kent heeeel beperkte pattern matching: catch-clauses
* Geen NPE: helaas heeft Scala wel null, vanwege compatibility -> tradeoff
* voorbeelden van option: Map.get, List.find, parseInt, etc.
* Twee doelen: selecteren goede case, en binden van variabelen in 1 stap
* Java kent heeeel beperkte pattern matching: catch-clauses
* Geen NPE: helaas heeft Scala wel null, vanwege compatibility -> tradeoff
* voorbeelden van option: Map.get, List.find, parseInt, etc.
* match is an expression too
* Of course case objects can be used to implement enums
* Of course case objects can be used to implement enums
* Of course case objects can be used to implement enums
* Of course case objects can be used to implement enums
* Of course case objects can be used to implement enums
Ook test frameworks
Proberen stukje realworld code van Java->Scala als Java programmeur->Idiomatische Scala
* TIOBE top-30: beating Groovy, Haskell
* TIOBE top-30: beating Groovy, Haskell
Java -> Scala voorbeeld: een Scala - methode wordt vertaald naar $minus$.
Veel conventies voor compiler gegenereerde classes.