Scala: functional programming for the imperative mind

Scala
Functional programming for the imperative mind
Scala
Functional programming for the imperative mind

                                    ‘of the nature of or
                                        expressing a
                                         command;
                                       commanding.’
                                        - imperative.
(n.d.).

                                          Dictionary.com
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
Outline
• Introduction
• Functional programming
• Scala features
• Java to Scala in three steps
• Scala community
• Wrap up
Roots
• Created by Martin Odersky
• Supported by EPFL Switzerland
What is Scala?
A programming language ...

• Runs on JVM  (and .Net)


• Statically typed
• Object Oriented
• Functional
• From scripting to enterprise apps
Scalable language
• Scalable language constructs:
  • Composition ‘in the small’
  • Composition ‘in the large’
• Java interoperability
• Performance on par with Java
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
What is



Functional
           Programming
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’)
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’)
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’)
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’)
Functional programming

• Focus on functions, not state
• Functions are values
• Recursion, not loops
• Immutability (‘referential transparency’)
• Schools of thought:
     pure and impure (‘pragmatic’)
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?)
FP in Scala

• First-class functions: functions are objects
  with pleasing syntax
• Immutability
• Algebraic data-types and pattern matching
• Parametric polymorphism (e.g. generics)
What are



  Scala’s
      Features
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)
Pure object orientation
No primitive types:
Pure object orientation
No primitive types:
Pure object orientation
Every operation is a method call:
              1+3           1.+(3)
Pure object orientation
 Every operation is a method call:
                1+3          1.+(3)
Console.println(“hi”)       Console println “hi”
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.
Pure object orientation
 Every operation is a method call:
                1+3          1.+(3)
Console.println(“hi”)       Console println “hi”
Pure object orientation
 Every operation is a method call:
                1+3          1.+(3)
Console.println(“hi”)       Console println “hi”
Pure object orientation
No static members, but singleton objects:
Type inference
• Types may be omitted in declarations




• Does not mean there is no type!
• Inference is local only
• Var/val: mutable vs. immutable
Type inference
Everything is an expression
Everything is an expression
Everything is an expression
Everything is an expression
Functional objects
• Functions are first-class values
• Function literals:
Functional objects
• Functions are first-class values
• Function literals:
    (x: Int) => x * 2
Functional objects
• Functions are first-class values
• Function literals:
    (x: Int) => x * 2
    val double = (x: Int) => x * 2
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?
Functional types
val double = (x: Int) => x * 2
        has type
(Int) => Int
Functional types
val double = (x: Int) => x * 2
        has type
(Int) => Int            Function1[Int,Int]
Passing functions
Since functions are values, we can
        pass them around:
Passing functions
But we can do this with anonymous classes...
Passing functions
But we can do this with anonymous classes...
Passing functions
But we can do this with anonymous classes...
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:
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:
Traits
• Compare trait with abstract class
• No interfaces, but: completely abstract traits
• Can mixin multiple traits, statically and
  dynamically
Traits as rich interfaces
Java interfaces have two consumers with
conflicting interests:
 1) Implementors
 2) Users
Traits as rich interfaces
Java interfaces have two consumers with
conflicting interests:
 1) Implementors
 2) Users
Traits as stackable
         modifications
• Situation: IntQueue interface (abstract trait),
  
 IntQueueImpl implementation
• We want to add logging and filtering to any
  IntQueue implementation
Traits as stackable
         modifications
• Situation: IntQueue interface (abstract trait),
  
 IntQueueImpl implementation
• We want to add logging and filtering to any
  IntQueue implementation
Traits as stackable
         modifications
• Situation: IntQueue interface (abstract trait),
  
 IntQueueImpl implementation
• We want to add logging and filtering to any
  IntQueue implementation
Pattern matching
Pattern matching
Pattern matching




    Yes, it prints 9
Pattern matching
• No more instanceof/typecasts
• No more visitor pattern
Pattern matching
• No more instanceof/typecasts
• No more visitor pattern
       No more NullPointerException:
Pattern matching & XML
• Scala has XML literals, can be matched
• Other literals can be matched as well
Language feature or




            Library
                      Support
Actors
• Message-based concurrency
• Actors exchange immutable messages
• Extract them by pattern matching
Actors
• Message-based concurrency
• Actors exchange immutable messages
• Extract them by pattern matching



 Looks like language feature, but is a library
Other library features
• Enums
• Map ‘syntax’
• Events
• Using ‘keyword’ (e.g. Java 7 ‘automatic
  resource management.’)
• Virtually all other Project Coin proposals
Other library features
• Enums
• Map ‘syntax’
• Events
• Using ‘keyword’ (e.g. Java 7 ‘automatic
  resource management.’)
• Virtually all other Project Coin proposals
Other library features
• Enums
• Map ‘syntax’
• Events
• Using ‘keyword’ (e.g. Java 7 ‘automatic
  resource management.’)
• Virtually all other Project Coin proposals
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...
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)
From Java to Scala


            In
       Three steps
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
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
What happens in the



    Scala
       Community
Scala progression

• Current version: 2.7.4
• Version 2.8 beta coming up:
 •   Package objects

 •   Named and default parameters

 •   Many library improvements
Tool support
•   Major IDEs (Eclipse,
    IntelliJ, NetBeans)
    supported

•   Maven support

•   Scaladoc

•   SBaz package manager
Wrapping up with




     Concluding
                   Remarks
Scala hitting mainstream?
Reports of first switchers
   Twitter, SAP, LinkedIn, Sony Pictures
Scala hitting mainstream?
Reports of first switchers
   Twitter, SAP, LinkedIn, Sony Pictures
April 2009: top-30 of TIOBE index
Scala hitting mainstream?
Reports of first switchers
   Twitter, SAP, LinkedIn, Sony Pictures
April 2009: top-30 of TIOBE index
Lots of books appearing
Scala hitting mainstream?

“If I were to pick a language today
other than Java, it would be Scala”




                  James Gosling,
                     ‘Father of Java’
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’
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
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
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.
More
  information
 http://www.scala-lang.org

     http://liftweb.net

Article Java Magazine 1/2009
Questions?
1 of 81

Recommended

Functional programming by
Functional programmingFunctional programming
Functional programmingijcd
1.4K views45 slides
Java 8 lambda by
Java 8 lambdaJava 8 lambda
Java 8 lambdaManav Prasad
2.3K views32 slides
Introduction to Scala by
Introduction to ScalaIntroduction to Scala
Introduction to ScalaMohammad Hossein Rimaz
5.8K views83 slides
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t... by
Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...Philip Schwarz
1.2K views46 slides
Clean code by
Clean codeClean code
Clean codeArturo Herrero
70K views88 slides
Java 8 Lambda and Streams by
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and StreamsVenkata Naga Ravi
3.9K views51 slides

More Related Content

What's hot

Quarkus - a next-generation Kubernetes Native Java framework by
Quarkus - a next-generation Kubernetes Native Java frameworkQuarkus - a next-generation Kubernetes Native Java framework
Quarkus - a next-generation Kubernetes Native Java frameworkSVDevOps
606 views42 slides
Elements of Java Language by
Elements of Java Language Elements of Java Language
Elements of Java Language Hitesh-Java
541 views66 slides
Introduction to java by
Introduction to java Introduction to java
Introduction to java Sandeep Rawat
1.4K views234 slides
The Evolution of Scala by
The Evolution of ScalaThe Evolution of Scala
The Evolution of ScalaMartin Odersky
44.4K views43 slides
Functional programming in Scala by
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scaladatamantra
1.7K views39 slides
Jetpack Compose beginner.pdf by
Jetpack Compose beginner.pdfJetpack Compose beginner.pdf
Jetpack Compose beginner.pdfAayushmaAgrawal
538 views46 slides

What's hot(20)

Quarkus - a next-generation Kubernetes Native Java framework by SVDevOps
Quarkus - a next-generation Kubernetes Native Java frameworkQuarkus - a next-generation Kubernetes Native Java framework
Quarkus - a next-generation Kubernetes Native Java framework
SVDevOps606 views
Elements of Java Language by Hitesh-Java
Elements of Java Language Elements of Java Language
Elements of Java Language
Hitesh-Java541 views
Introduction to java by Sandeep Rawat
Introduction to java Introduction to java
Introduction to java
Sandeep Rawat1.4K views
The Evolution of Scala by Martin Odersky
The Evolution of ScalaThe Evolution of Scala
The Evolution of Scala
Martin Odersky44.4K views
Functional programming in Scala by datamantra
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala
datamantra1.7K views
Core Java Tutorials by Mahika Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
Mahika Tutorials1.4K views
Java 9 New Features by Ali BAKAN
Java 9 New FeaturesJava 9 New Features
Java 9 New Features
Ali BAKAN195 views
OOP java by xball977
OOP javaOOP java
OOP java
xball97716.6K views
Clean Code I - Best Practices by Theo Jungeblut
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best Practices
Theo Jungeblut15K views
Java 8 Lambda Built-in Functional Interfaces by Ganesh Samarthyam
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
Ganesh Samarthyam3.2K views
Spring boot by sdeeg
Spring bootSpring boot
Spring boot
sdeeg26.6K views
Kotlin vs Java | Edureka by Edureka!
Kotlin vs Java | EdurekaKotlin vs Java | Edureka
Kotlin vs Java | Edureka
Edureka!488 views
Why TypeScript? by FITC
Why TypeScript?Why TypeScript?
Why TypeScript?
FITC3.9K views
Basic Concepts of OOPs (Object Oriented Programming in Java) by Michelle Anne Meralpis
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)

Viewers also liked

Introduction to Functional Programming with Scala by
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scalapramode_ce
57.6K views75 slides
Functional Programming Fundamentals by
Functional Programming FundamentalsFunctional Programming Fundamentals
Functional Programming FundamentalsShahriar Hyder
12.1K views66 slides
Introduction to Monads in Scala (1) by
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)stasimus
10.2K views45 slides
Developers Summit 2015 - Scala Monad by
Developers Summit 2015 - Scala MonadDevelopers Summit 2015 - Scala Monad
Developers Summit 2015 - Scala MonadSangwon Han
1.9K views33 slides
Scala Talk at FOSDEM 2009 by
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
37.2K views42 slides
Advanced Functional Programming in Scala by
Advanced Functional Programming in ScalaAdvanced Functional Programming in Scala
Advanced Functional Programming in ScalaPatrick Nicolas
17K views77 slides

Viewers also liked(20)

Introduction to Functional Programming with Scala by pramode_ce
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
pramode_ce57.6K views
Functional Programming Fundamentals by Shahriar Hyder
Functional Programming FundamentalsFunctional Programming Fundamentals
Functional Programming Fundamentals
Shahriar Hyder12.1K views
Introduction to Monads in Scala (1) by stasimus
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)
stasimus10.2K views
Developers Summit 2015 - Scala Monad by Sangwon Han
Developers Summit 2015 - Scala MonadDevelopers Summit 2015 - Scala Monad
Developers Summit 2015 - Scala Monad
Sangwon Han1.9K views
Scala Talk at FOSDEM 2009 by Martin Odersky
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
Martin Odersky37.2K views
Advanced Functional Programming in Scala by Patrick Nicolas
Advanced Functional Programming in ScalaAdvanced Functional Programming in Scala
Advanced Functional Programming in Scala
Patrick Nicolas17K views
Java 8 - functional features by Rafal Rybacki
Java 8 - functional featuresJava 8 - functional features
Java 8 - functional features
Rafal Rybacki499 views
Object oriented-programming-vs-procedural-programming by kukurmutta
Object oriented-programming-vs-procedural-programmingObject oriented-programming-vs-procedural-programming
Object oriented-programming-vs-procedural-programming
kukurmutta3.3K views
Why functional why scala by Neville Li
Why functional  why scala Why functional  why scala
Why functional why scala
Neville Li1.7K views
Scala the language matters by Xiaojun REN
Scala the language mattersScala the language matters
Scala the language matters
Xiaojun REN677 views
Introduction to Monads in Scala (2) by stasimus
Introduction to Monads in Scala (2)Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)
stasimus6.1K views
Monad presentation scala as a category by samthemonad
Monad presentation   scala as a categoryMonad presentation   scala as a category
Monad presentation scala as a category
samthemonad2K views
Introduction to scala for a c programmer by Girish Kumar A L
Introduction to scala for a c programmerIntroduction to scala for a c programmer
Introduction to scala for a c programmer
Girish Kumar A L678 views
Jump Start into Apache Spark (Seattle Spark Meetup) by Denny Lee
Jump Start into Apache Spark (Seattle Spark Meetup)Jump Start into Apache Spark (Seattle Spark Meetup)
Jump Start into Apache Spark (Seattle Spark Meetup)
Denny Lee1.3K views
Thinking functional-in-scala by Knoldus Inc.
Thinking functional-in-scalaThinking functional-in-scala
Thinking functional-in-scala
Knoldus Inc.1.6K views
Introduction to Option monad in Scala by Jan Krag
Introduction to Option monad in ScalaIntroduction to Option monad in Scala
Introduction to Option monad in Scala
Jan Krag11.2K views
Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa... by Databricks
Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...
Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...
Databricks4.3K views

Similar to Scala: functional programming for the imperative mind

javascript teach by
javascript teachjavascript teach
javascript teachguest3732fa
1.2K views155 slides
JSBootcamp_White by
JSBootcamp_WhiteJSBootcamp_White
JSBootcamp_Whiteguest3732fa
907 views155 slides
LISP: How I Learned To Stop Worrying And Love Parantheses by
LISP: How I Learned To Stop Worrying And Love ParanthesesLISP: How I Learned To Stop Worrying And Love Parantheses
LISP: How I Learned To Stop Worrying And Love ParanthesesDominic Graefen
896 views56 slides
Introductory func prog by
Introductory func progIntroductory func prog
Introductory func progOleksandr Khomenko
517 views24 slides
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16 by
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16Innovecs
621 views24 slides
Functional programming with Java 8 by
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8Talha Ocakçı
1.2K views106 slides

Similar to Scala: functional programming for the imperative mind(20)

javascript teach by guest3732fa
javascript teachjavascript teach
javascript teach
guest3732fa1.2K views
JSBootcamp_White by guest3732fa
JSBootcamp_WhiteJSBootcamp_White
JSBootcamp_White
guest3732fa907 views
LISP: How I Learned To Stop Worrying And Love Parantheses by Dominic Graefen
LISP: How I Learned To Stop Worrying And Love ParanthesesLISP: How I Learned To Stop Worrying And Love Parantheses
LISP: How I Learned To Stop Worrying And Love Parantheses
Dominic Graefen896 views
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16 by Innovecs
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
Innovecs621 views
Functional programming with Java 8 by Talha Ocakçı
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
Talha Ocakçı1.2K views
Introduction to functional programming (In Arabic) by Omar Abdelhafith
Introduction to functional programming (In Arabic)Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)
Omar Abdelhafith436 views
Programming Android Application in Scala. by Brian Hsu
Programming Android Application in Scala.Programming Android Application in Scala.
Programming Android Application in Scala.
Brian Hsu2.4K views
scalaliftoff2009.pdf by Hiroshi Ono
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono746 views
scalaliftoff2009.pdf by Hiroshi Ono
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono1.4K views
scalaliftoff2009.pdf by Hiroshi Ono
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono472 views
scalaliftoff2009.pdf by Hiroshi Ono
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono463 views
An Introduction to Scala - Blending OO and Functional Paradigms by Miles Sabin
An Introduction to Scala - Blending OO and Functional ParadigmsAn Introduction to Scala - Blending OO and Functional Paradigms
An Introduction to Scala - Blending OO and Functional Paradigms
Miles Sabin767 views
Introduction to Erlang Programming Language by Yasas Gunarathne
Introduction to Erlang Programming LanguageIntroduction to Erlang Programming Language
Introduction to Erlang Programming Language
Yasas Gunarathne97 views
javascript by Kaya Ota
javascript javascript
javascript
Kaya Ota367 views

More from Sander Mak (@Sander_Mak)

Scalable Application Development @ Picnic by
Scalable Application Development @ PicnicScalable Application Development @ Picnic
Scalable Application Development @ PicnicSander Mak (@Sander_Mak)
239 views20 slides
Coding Your Way to Java 13 by
Coding Your Way to Java 13Coding Your Way to Java 13
Coding Your Way to Java 13Sander Mak (@Sander_Mak)
414 views80 slides
Coding Your Way to Java 12 by
Coding Your Way to Java 12Coding Your Way to Java 12
Coding Your Way to Java 12Sander Mak (@Sander_Mak)
2K views69 slides
Java Modularity: the Year After by
Java Modularity: the Year AfterJava Modularity: the Year After
Java Modularity: the Year AfterSander Mak (@Sander_Mak)
913 views109 slides
Desiging for Modularity with Java 9 by
Desiging for Modularity with Java 9Desiging for Modularity with Java 9
Desiging for Modularity with Java 9Sander Mak (@Sander_Mak)
1.9K views80 slides
Modules or microservices? by
Modules or microservices?Modules or microservices?
Modules or microservices?Sander Mak (@Sander_Mak)
5.9K views117 slides

More from Sander Mak (@Sander_Mak)(20)

Recently uploaded

Empathic Computing: Delivering the Potential of the Metaverse by
Empathic Computing: Delivering  the Potential of the MetaverseEmpathic Computing: Delivering  the Potential of the Metaverse
Empathic Computing: Delivering the Potential of the MetaverseMark Billinghurst
470 views80 slides
Uni Systems for Power Platform.pptx by
Uni Systems for Power Platform.pptxUni Systems for Power Platform.pptx
Uni Systems for Power Platform.pptxUni Systems S.M.S.A.
50 views21 slides
20231123_Camunda Meetup Vienna.pdf by
20231123_Camunda Meetup Vienna.pdf20231123_Camunda Meetup Vienna.pdf
20231123_Camunda Meetup Vienna.pdfPhactum Softwareentwicklung GmbH
28 views73 slides
STPI OctaNE CoE Brochure.pdf by
STPI OctaNE CoE Brochure.pdfSTPI OctaNE CoE Brochure.pdf
STPI OctaNE CoE Brochure.pdfmadhurjyapb
12 views1 slide
ChatGPT and AI for Web Developers by
ChatGPT and AI for Web DevelopersChatGPT and AI for Web Developers
ChatGPT and AI for Web DevelopersMaximiliano Firtman
181 views82 slides
Voice Logger - Telephony Integration Solution at Aegis by
Voice Logger - Telephony Integration Solution at AegisVoice Logger - Telephony Integration Solution at Aegis
Voice Logger - Telephony Integration Solution at AegisNirmal Sharma
17 views1 slide

Recently uploaded(20)

Empathic Computing: Delivering the Potential of the Metaverse by Mark Billinghurst
Empathic Computing: Delivering  the Potential of the MetaverseEmpathic Computing: Delivering  the Potential of the Metaverse
Empathic Computing: Delivering the Potential of the Metaverse
Mark Billinghurst470 views
STPI OctaNE CoE Brochure.pdf by madhurjyapb
STPI OctaNE CoE Brochure.pdfSTPI OctaNE CoE Brochure.pdf
STPI OctaNE CoE Brochure.pdf
madhurjyapb12 views
Voice Logger - Telephony Integration Solution at Aegis by Nirmal Sharma
Voice Logger - Telephony Integration Solution at AegisVoice Logger - Telephony Integration Solution at Aegis
Voice Logger - Telephony Integration Solution at Aegis
Nirmal Sharma17 views
Understanding GenAI/LLM and What is Google Offering - Felix Goh by NUS-ISS
Understanding GenAI/LLM and What is Google Offering - Felix GohUnderstanding GenAI/LLM and What is Google Offering - Felix Goh
Understanding GenAI/LLM and What is Google Offering - Felix Goh
NUS-ISS41 views
Data-centric AI and the convergence of data and model engineering: opportunit... by Paolo Missier
Data-centric AI and the convergence of data and model engineering:opportunit...Data-centric AI and the convergence of data and model engineering:opportunit...
Data-centric AI and the convergence of data and model engineering: opportunit...
Paolo Missier34 views
RADIUS-Omnichannel Interaction System by RADIUS
RADIUS-Omnichannel Interaction SystemRADIUS-Omnichannel Interaction System
RADIUS-Omnichannel Interaction System
RADIUS15 views
Perth MeetUp November 2023 by Michael Price
Perth MeetUp November 2023 Perth MeetUp November 2023
Perth MeetUp November 2023
Michael Price15 views
handbook for web 3 adoption.pdf by Liveplex
handbook for web 3 adoption.pdfhandbook for web 3 adoption.pdf
handbook for web 3 adoption.pdf
Liveplex19 views
Attacking IoT Devices from a Web Perspective - Linux Day by Simone Onofri
Attacking IoT Devices from a Web Perspective - Linux Day Attacking IoT Devices from a Web Perspective - Linux Day
Attacking IoT Devices from a Web Perspective - Linux Day
Simone Onofri15 views
The details of description: Techniques, tips, and tangents on alternative tex... by BookNet Canada
The details of description: Techniques, tips, and tangents on alternative tex...The details of description: Techniques, tips, and tangents on alternative tex...
The details of description: Techniques, tips, and tangents on alternative tex...
BookNet Canada121 views
How the World's Leading Independent Automotive Distributor is Reinventing Its... by NUS-ISS
How the World's Leading Independent Automotive Distributor is Reinventing Its...How the World's Leading Independent Automotive Distributor is Reinventing Its...
How the World's Leading Independent Automotive Distributor is Reinventing Its...
NUS-ISS15 views
Spesifikasi Lengkap ASUS Vivobook Go 14 by Dot Semarang
Spesifikasi Lengkap ASUS Vivobook Go 14Spesifikasi Lengkap ASUS Vivobook Go 14
Spesifikasi Lengkap ASUS Vivobook Go 14
Dot Semarang35 views
Digital Product-Centric Enterprise and Enterprise Architecture - Tan Eng Tsze by NUS-ISS
Digital Product-Centric Enterprise and Enterprise Architecture - Tan Eng TszeDigital Product-Centric Enterprise and Enterprise Architecture - Tan Eng Tsze
Digital Product-Centric Enterprise and Enterprise Architecture - Tan Eng Tsze
NUS-ISS19 views
AI: mind, matter, meaning, metaphors, being, becoming, life values by Twain Liu 刘秋艳
AI: mind, matter, meaning, metaphors, being, becoming, life valuesAI: mind, matter, meaning, metaphors, being, becoming, life values
AI: mind, matter, meaning, metaphors, being, becoming, life values

Scala: functional programming for the imperative mind

  • 1. Scala Functional programming for the imperative mind
  • 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
  • 4. Outline • Introduction • Functional programming • Scala features • Java to Scala in three steps • Scala community • Wrap up
  • 5. Roots • Created by Martin Odersky • Supported by EPFL Switzerland
  • 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
  • 9. What is Functional Programming
  • 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)
  • 17. What are Scala’s Features
  • 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)
  • 19. Pure object orientation No primitive types:
  • 20. Pure object orientation No primitive types:
  • 21. Pure object orientation Every operation is a method call: 1+3 1.+(3)
  • 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”
  • 26. Pure object orientation No static members, but singleton objects:
  • 27. Type inference • Types may be omitted in declarations • Does not mean there is no type! • Inference is local only • Var/val: mutable vs. immutable
  • 29. Everything is an expression
  • 30. Everything is an expression
  • 31. Everything is an expression
  • 32. Everything is an expression
  • 33. Functional objects • Functions are first-class values • Function literals:
  • 34. Functional objects • Functions are first-class values • Function literals: (x: Int) => x * 2
  • 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?
  • 37. Functional types val double = (x: Int) => x * 2 has type (Int) => Int
  • 38. Functional types val double = (x: Int) => x * 2 has type (Int) => Int Function1[Int,Int]
  • 39. Passing functions Since functions are values, we can pass them around:
  • 40. Passing functions But we can do this with anonymous classes...
  • 41. Passing functions But we can do this with anonymous classes...
  • 42. Passing functions But we can do this with anonymous classes...
  • 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
  • 53. Pattern matching Yes, it prints 9
  • 54. Pattern matching • No more instanceof/typecasts • No more visitor pattern
  • 55. Pattern matching • No more instanceof/typecasts • No more visitor pattern No more NullPointerException:
  • 56. Pattern matching & XML • Scala has XML literals, can be matched • Other literals can be matched as well
  • 57. Language feature or Library Support
  • 58. Actors • Message-based concurrency • Actors exchange immutable messages • Extract them by pattern matching
  • 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)
  • 65. From Java to Scala In Three steps
  • 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
  • 68. What happens in the Scala Community
  • 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
  • 71. Wrapping up with Concluding Remarks
  • 72. Scala hitting mainstream? Reports of first switchers Twitter, SAP, LinkedIn, Sony Pictures
  • 73. Scala hitting mainstream? Reports of first switchers Twitter, SAP, LinkedIn, Sony Pictures April 2009: top-30 of TIOBE index
  • 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

Editor's Notes

  1. 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.
  2. 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.
  3. 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.
  4. Odersky: co-designer generics, original author javac. Wellicht had hier oracle logo moeten staan :)
  5. *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
  6. Scala redelijk uniek in samenvoegen OO+FP OCaml en F# zijn toch meer FP met een OO systeem er aan geplakt.
  7. Recursie niet alleen in functies, ook in data (bomen, lijsten)
  8. Recursie niet alleen in functies, ook in data (bomen, lijsten)
  9. Recursie niet alleen in functies, ook in data (bomen, lijsten)
  10. Recursie niet alleen in functies, ook in data (bomen, lijsten)
  11. Recursie niet alleen in functies, ook in data (bomen, lijsten)
  12. Recursie niet alleen in functies, ook in data (bomen, lijsten)
  13. Recursie niet alleen in functies, ook in data (bomen, lijsten)
  14. Recursie niet alleen in functies, ook in data (bomen, lijsten)
  15. Recursie niet alleen in functies, ook in data (bomen, lijsten)
  16. Recursie niet alleen in functies, ook in data (bomen, lijsten)
  17. Recursie niet alleen in functies, ook in data (bomen, lijsten)
  18. Nieuwe paradigma&#x2019;s hebben killer-app nodig OO had GUIs, bij FP concurrency? Typesysteem: niet noodzakelijk voor FP, traditioneel wel focus
  19. Zonder diep in te gaan, voor we features gaan bekijken, dit is hoe Scala FP bevat.
  20. *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
  21. Extenden van Java class (extends ook voor interfaces) Type Unit -> void in Java hashCode -> hashCode() , haakjes weglaten. Soort van autoboxing, maar beter
  22. * + is methode naam, kan je zelf op een class implementeren * Leestekens legale identifiers in Scala * Operator notatie ook te gebruiken met &#x2018;normale&#x2019; methode namen * In Java discussie: operator overloadig BigInts (en wat voor matrix etc.)? Scala: just do it.
  23. * + is methode naam, kan je zelf op een class implementeren * Leestekens legale identifiers in Scala * Operator notatie ook te gebruiken met &#x2018;normale&#x2019; methode namen * In Java discussie: operator overloadig BigInts (en wat voor matrix etc.)? Scala: just do it.
  24. * + is methode naam, kan je zelf op een class implementeren * Leestekens legale identifiers in Scala * Operator notatie ook te gebruiken met &#x2018;normale&#x2019; methode namen * In Java discussie: operator overloadig BigInts (en wat voor matrix etc.)? Scala: just do it.
  25. * + is methode naam, kan je zelf op een class implementeren * Leestekens legale identifiers in Scala * Operator notatie ook te gebruiken met &#x2018;normale&#x2019; methode namen * In Java discussie: operator overloadig BigInts (en wat voor matrix etc.)? Scala: just do it.
  26. * + is methode naam, kan je zelf op een class implementeren * Leestekens legale identifiers in Scala * Operator notatie ook te gebruiken met &#x2018;normale&#x2019; methode namen * In Java discussie: operator overloadig BigInts (en wat voor matrix etc.)? Scala: just do it.
  27. *Java statics niet echt OO. Scala: Classes->te instantieren, singleton objects->&#xE9;&#xE9;n instantie *Zelfde naam: companions -> toegang tot private members *haakjes mogen weg bij methode aanroep zonder params; puntkomma&#x2019;s ook optioneel! *main methode op object Main, entrypoint applicatie
  28. * Vorige slide goed opgelet: geen return type!
  29. * Zijn natuurlijk allemaal op ISKA over closures geweest, maar toch een opfrisser * Java heeft Anon. classes -> beperkingen, verbose (interface nodig), daarom weinig gebruikt
  30. * Zijn natuurlijk allemaal op ISKA over closures geweest, maar toch een opfrisser * Java heeft Anon. classes -> beperkingen, verbose (interface nodig), daarom weinig gebruikt
  31. * Zijn natuurlijk allemaal op ISKA over closures geweest, maar toch een opfrisser * Java heeft Anon. classes -> beperkingen, verbose (interface nodig), daarom weinig gebruikt
  32. * Zijn natuurlijk allemaal op ISKA over closures geweest, maar toch een opfrisser * Java heeft Anon. classes -> beperkingen, verbose (interface nodig), daarom weinig gebruikt
  33. * Function0 tot Function22 op deze manier beschikbaar
  34. * Function0 tot Function22 op deze manier beschikbaar
  35. * Function0 tot Function22 op deze manier beschikbaar
  36. * Function0 tot Function22 op deze manier beschikbaar
  37. * Function0 tot Function22 op deze manier beschikbaar
  38. * Function0 tot Function22 op deze manier beschikbaar
  39. * Function0 tot Function22 op deze manier beschikbaar
  40. Scala gaat nog verder, zelf control structures maken (by-name params)
  41. * 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
  42. * Traits are used in this fashion a lot for the Scala collection libs
  43. * 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!
  44. * 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!
  45. * 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!
  46. * geen new keyword nodig: case class is class + companion object met apply method! * Sealed abstract class: compiler kan checken of alle cases gedekt zijn
  47. * geen new keyword nodig: case class is class + companion object met apply method! * Sealed abstract class: compiler kan checken of alle cases gedekt zijn
  48. * geen new keyword nodig: case class is class + companion object met apply method! * Sealed abstract class: compiler kan checken of alle cases gedekt zijn
  49. * 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.
  50. * 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.
  51. * match is an expression too
  52. * Of course case objects can be used to implement enums
  53. * Of course case objects can be used to implement enums
  54. * Of course case objects can be used to implement enums
  55. * Of course case objects can be used to implement enums
  56. * Of course case objects can be used to implement enums
  57. Ook test frameworks
  58. Proberen stukje realworld code van Java->Scala als Java programmeur->Idiomatische Scala
  59. * TIOBE top-30: beating Groovy, Haskell
  60. * TIOBE top-30: beating Groovy, Haskell
  61. Java -> Scala voorbeeld: een Scala - methode wordt vertaald naar $minus$. Veel conventies voor compiler gegenereerde classes.