SlideShare a Scribd company logo
Scala
or: functional programming
from a python developer’s perspective
Gabriele Alese
http://gabale.se
Hello.
object HelloWorld extends App {
println("Hello World!")
}
apropos Scala
• «Scala is a pure-bred object-oriented language. Conceptually,
every value is an object and every operation is a method-call. The
language supports advanced component architectures through
classes and traits.»
• «Scala is also a full-blown functional language. It has everything
you would expect, including first-class functions, a library with
efficient immutable data structures, and a general preference of
immutability over mutation.»
• A sane approach to the JVM
• Flexibility
• Interoperability
• Excellent community
• Better documentation (mostly)
Why Scala?
• Static types
• Rich type system
• Functions are first-class citizens
• Stress on immutability
• Case classes (traits, objects, …)
• Pattern matching
• Rich collections (List, HashMap, Seq, Vector)
• Operator overloading
• Interoperability with Java libraries
• REPL and worksheets (Eclipse, IntelliJ)
Why I like Scala so much?
Static types
class Phrase(value: String) {
def wordCount: Map[String, Int] = {
val wordsMap = words map (_ -> 1)
wordsMap.foldLeft(Map.empty[String, Int]) {
case (acc, (key, _)) => acc + (key -> (acc.getOrElse(key, 0) + 1))
}
}
def words: Seq[String] = {
value.toLowerCase.split("[^a-zA-Z0-9']+")
}
}
Static types
• Compile time checking
• Your IDE will be much more helpful
• Encourages encapsulation
• Limits your ‘ability’ to write code before thinking
• Inferred types greatly reduce boilerplate
• … no more “‘NoneType’ object has no attribute…”

Rich type system
• Monads [Option, Try, Either, …]

«A monad is a container type together with map and flatMap methods defined on it.»
• Functions [Function1, Function2, …]
• Generic types [+T, -T]
• Higher kinded types

trait Functor[F[_]] {
def map[A, B](fa: F[A])(f: A => B): F[B]
}
• Structural types

def setElementText(element : {def setText(text : String)}, text : String)
Functions as first-class citizens
sealed trait List[A] {
def map[A](f: A => A): List[A]
Functions as first-class citizens
• Higher-order functions (i.e. sum in terms of fold)
• Anonymous functions

(x: Int, y: Int) => x + y
• Easily transform collections with map
Stress on immutability
«[…] there can never be surprises in logic.»
– L. Wittgenstein
Hopefully, there should never be surprises in code.
Stress on immutability
object LongestIncreasingSubsequence {
def apply(sequence: Seq[Int]): Seq[Int] = {
val validSubsequences = iterateAndDropHead(Seq(sequence), sequence)
validSubsequences
.map(findIncreasingSubsequence)
.sortBy(_.length)(Ordering[Int].reverse)
.head
}
@tailrec
def iterateAndDropHead(folded: Seq[Seq[Int]], remaining: Seq[Int]): Seq[Seq[Int]] = {
remaining match {
case head :: Nil => folded
case head :: tail => iterateAndDropHead(folded :+ tail, tail)
}
}
def findIncreasingSubsequence(sequence: Seq[Int]): Seq[Int] = {
sequence.foldLeft(Seq(sequence.head)) {
(acc, el) => if(acc.last < el) acc :+ el else acc
}
}
}
Case classes
case class Person(firstName: String, lastName: String)
val randomGuy = Person("Gabriele", "Alese")
randomGuy match {
case Person("Gabriele", _) => println("Hello Gabriele!")
case Person("Vincent", _) => println("Hello, Vincent!")
case _ => println("I've never seen you before")
}
Case classes
• Free accessors (and mutators, if you must)
• Free equals() and hashCode()
• Free toString()
• Free copy()
• No need to use new
• Free apply and unapply methods 

on the companion object (see pattern matching)
Pattern matching
sealed abstract class Expression
case class X() extends Expression
case class Const(value : Int) extends Expression
case class Add(left : Expression, right : Expression) extends Expression
case class Mult(left : Expression, right : Expression) extends Expression
case class Neg(expr : Expression) extends Expression
def eval(expression : Expression, xValue : Int) : Int = expression match {
case X() => xValue
case Const(cst) => cst
case Add(left, right) => eval(left, xValue) + eval(right, xValue)
case Mult(left, right) => eval(left, xValue) * eval(right, xValue)
case Neg(expr) => - eval(expr, xValue)
}
Rich collections
def sort(xs: Array[Int]): Array[Int] = {
if (xs.length <= 1) xs
else {
val pivot = xs(xs.length / 2)
Array.concat(
sort(xs filter (pivot >)),
xs filter (pivot ==),
sort(xs filter (pivot <))
)
}
}
Rich collections
• map
• foreach
• filter (and filterNot)
• zip
• find
• drop (and dropWhile)
• foldLeft (and foldRight)
Rich collections
def dropWhile[A](l: List[A])(f: A => Boolean): List[A] =
l match {
case Cons(head, tail) if f(head) => dropWhile(tail)(f)
case _ => l
}
def foldRight[A, B](list: List[A], initial: B)(f: (A, B) => B): B = {
list match {
case Nil => initial
case Cons(head, tail) => f(head, foldRight(tail, initial)(f))
}
}
def foldLeft[A, B](as: List[A], initial: B)(f: (B, A) => B): B = {
as match {
case Nil => initial
case Cons(head, tail) => foldLeft(tail, f(initial, head))(f)
}
}
def map[A, B](list: List[A])(f: A => B): List[B] = {
foldRight(list, Nil: List[B])((a, b) => Cons(f(a), b))
}
def filter[A](list: List[A])(f: A => Boolean): List[A] = {
foldRight(list, Nil: List[A])((a, b) => if (f(a)) Cons(a, b) else b)
}
def flatMap[A, B](list: List[A])(f: A => List[B]): List[B] = {
concat(map(list)(f))
}
}
Operator overloading
package it.alese.scacchirossi.scacchirossi
import it.alese.scacchirossi.scacchirossi.board.{Column, Row}
case class Position(column: Column, row: Row) {
val x: Int = column.toInt
val y: Int = row.toInt
def to(toPosition: Position): List[Position] = {
Move(this, toPosition).intermediatePositions
}
def +(x: Int, y: Int) = {
val col = if (this.x + x != 0) Column(this.x + x) else this.column
val row = if (this.y + y != 0) Row(this.y + y) else this.row
new Position(col, row)
}
…
}
object Position {
def apply(position: String): Position = {
require(position.length == 2, "Illegal coordinate string")
new Position(Column(position(0)), Row(position(1).asDigit))
}
…
}
package it.alese.scacchirossi.scacchirossi
class PositionTest extends WordSpec with Matchers {
"A position" should {
…
"return a new position if summed to an offset" in {
Position("A1") + (1,1) shouldEqual Position("B2")
Position("A1") + (0,1) shouldEqual Position("A2")
}
"return a range of contiguous vertical positions" in {
Position("A1") to Position("A4")
shouldEqual
List(Position("A1"), Position("A2"), Position("A3"), Position("A4"))
}
}
Operator overloading
• Expressivity 

(especially combined with infix notation)
• Define intuitive operations between types
• Pretty powerful DSLs

(Like ScalaTest)
Interoperability with Java libraries
package it.alese.emailchecker
import java.io.{InputStreamReader, BufferedReader, PrintWriter}
import java.net.Socket
case class TelnetSession(socket: Socket, input: PrintWriter, output: BufferedReader) {
def allowsConnections: Boolean = {
Reply(output.readLine).code match {
case "220" => true
case _ => false
}
}
def send(command: String): String = {
input.println(command)
output.readLine
}
def close(): Unit = {
send("quit")
socket.close()
}
}
object TelnetSession {
def apply(host: String): TelnetSession = {
val socket = new Socket(host, 25)
new TelnetSession(
socket,
new PrintWriter(socket.getOutputStream, true),
new BufferedReader(
new InputStreamReader(socket.getInputStream)
)
)
}
}
Interoperability with Java libraries
• If you can’t find a Scala library for that, chances are
that you’ll find a Java equivalent

(Good luck with the documentation!)
• Appealing for Java programmers

(or young professionals fresh out of “university Java”)
• Stronger community

(IMHO: many Scala enthusiasts are Java seniors)
REPL
???
Thank you.
Gabriele Alese
http://gabale.se

More Related Content

What's hot

Introducing scala
Introducing scalaIntroducing scala
Introducing scala
Meetu Maltiar
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Meetu Maltiar
 
Data Structures In Scala
Data Structures In ScalaData Structures In Scala
Data Structures In Scala
Knoldus Inc.
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
Tomer Gabel
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
IndicThreads
 
Exploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in ScalaExploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in Scala
Jorge Vásquez
 
Ten-page Brief Overview of Swift for Scala Developers
Ten-page Brief Overview of Swift for Scala DevelopersTen-page Brief Overview of Swift for Scala Developers
Ten-page Brief Overview of Swift for Scala Developers
ihji
 
Scala parallel-collections
Scala parallel-collectionsScala parallel-collections
Scala parallel-collections
Knoldus Inc.
 
Scala Parallel Collections
Scala Parallel CollectionsScala Parallel Collections
Scala Parallel Collections
Aleksandar Prokopec
 
High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scaladjspiewak
 
Functional programming with_scala
Functional programming with_scalaFunctional programming with_scala
Functional programming with_scala
Raymond Tay
 
Traits in scala
Traits in scalaTraits in scala
Traits in scala
Knoldus Inc.
 
A Prelude of Purity: Scaling Back ZIO
A Prelude of Purity: Scaling Back ZIOA Prelude of Purity: Scaling Back ZIO
A Prelude of Purity: Scaling Back ZIO
Jorge Vásquez
 
scala-101
scala-101scala-101
scala-101
Joe Conley
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
league
 
Exploring type level programming in Scala
Exploring type level programming in ScalaExploring type level programming in Scala
Exploring type level programming in Scala
Jorge Vásquez
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in Scala
Vladimir Kostyukov
 
Scala training workshop 02
Scala training workshop 02Scala training workshop 02
Scala training workshop 02
Nguyen Tuan
 

What's hot (19)

Introducing scala
Introducing scalaIntroducing scala
Introducing scala
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Data Structures In Scala
Data Structures In ScalaData Structures In Scala
Data Structures In Scala
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
 
Exploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in ScalaExploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in Scala
 
Ten-page Brief Overview of Swift for Scala Developers
Ten-page Brief Overview of Swift for Scala DevelopersTen-page Brief Overview of Swift for Scala Developers
Ten-page Brief Overview of Swift for Scala Developers
 
Scala parallel-collections
Scala parallel-collectionsScala parallel-collections
Scala parallel-collections
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Scala Parallel Collections
Scala Parallel CollectionsScala Parallel Collections
Scala Parallel Collections
 
High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scala
 
Functional programming with_scala
Functional programming with_scalaFunctional programming with_scala
Functional programming with_scala
 
Traits in scala
Traits in scalaTraits in scala
Traits in scala
 
A Prelude of Purity: Scaling Back ZIO
A Prelude of Purity: Scaling Back ZIOA Prelude of Purity: Scaling Back ZIO
A Prelude of Purity: Scaling Back ZIO
 
scala-101
scala-101scala-101
scala-101
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Exploring type level programming in Scala
Exploring type level programming in ScalaExploring type level programming in Scala
Exploring type level programming in Scala
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in Scala
 
Scala training workshop 02
Scala training workshop 02Scala training workshop 02
Scala training workshop 02
 

Similar to Scala or functional programming from a python developer's perspective

(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 
Meet scala
Meet scalaMeet scala
Meet scala
Wojciech Pituła
 
Scala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldScala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereld
Werner Hofstra
 
Power of functions in a typed world
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed world
Debasish Ghosh
 
Comparing Haskell & Scala
Comparing Haskell & ScalaComparing Haskell & Scala
Comparing Haskell & Scala
Martin Ockajak
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
Constantine Nosovsky
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
ehsoon
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meetMario Fusco
 
Scala introduction
Scala introductionScala introduction
Scala introduction
Yardena Meymann
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
Types by Adform Research
Types by Adform ResearchTypes by Adform Research
Types by Adform ResearchVasil Remeniuk
 
Frp2016 3
Frp2016 3Frp2016 3
Frp2016 3
Kirill Kozlov
 
Scala. Introduction to FP. Monads
Scala. Introduction to FP. MonadsScala. Introduction to FP. Monads
Scala. Introduction to FP. Monads
Kirill Kozlov
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
Knoldus Inc.
 
Short Reference Card for R users.
Short Reference Card for R users.Short Reference Card for R users.
Short Reference Card for R users.
Dr. Volkan OBAN
 

Similar to Scala or functional programming from a python developer's perspective (20)

An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
Meet scala
Meet scalaMeet scala
Meet scala
 
Scala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldScala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereld
 
Power of functions in a typed world
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed world
 
Comparing Haskell & Scala
Comparing Haskell & ScalaComparing Haskell & Scala
Comparing Haskell & Scala
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
Types by Adform Research
Types by Adform ResearchTypes by Adform Research
Types by Adform Research
 
Frp2016 3
Frp2016 3Frp2016 3
Frp2016 3
 
Scala
ScalaScala
Scala
 
Scala. Introduction to FP. Monads
Scala. Introduction to FP. MonadsScala. Introduction to FP. Monads
Scala. Introduction to FP. Monads
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
 
Short Reference Card for R users.
Short Reference Card for R users.Short Reference Card for R users.
Short Reference Card for R users.
 

Recently uploaded

The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
UiPathCommunity
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 

Recently uploaded (20)

The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 

Scala or functional programming from a python developer's perspective

  • 1. Scala or: functional programming from a python developer’s perspective Gabriele Alese http://gabale.se
  • 2. Hello. object HelloWorld extends App { println("Hello World!") }
  • 3. apropos Scala • «Scala is a pure-bred object-oriented language. Conceptually, every value is an object and every operation is a method-call. The language supports advanced component architectures through classes and traits.» • «Scala is also a full-blown functional language. It has everything you would expect, including first-class functions, a library with efficient immutable data structures, and a general preference of immutability over mutation.»
  • 4. • A sane approach to the JVM • Flexibility • Interoperability • Excellent community • Better documentation (mostly) Why Scala?
  • 5. • Static types • Rich type system • Functions are first-class citizens • Stress on immutability • Case classes (traits, objects, …) • Pattern matching • Rich collections (List, HashMap, Seq, Vector) • Operator overloading • Interoperability with Java libraries • REPL and worksheets (Eclipse, IntelliJ) Why I like Scala so much?
  • 6. Static types class Phrase(value: String) { def wordCount: Map[String, Int] = { val wordsMap = words map (_ -> 1) wordsMap.foldLeft(Map.empty[String, Int]) { case (acc, (key, _)) => acc + (key -> (acc.getOrElse(key, 0) + 1)) } } def words: Seq[String] = { value.toLowerCase.split("[^a-zA-Z0-9']+") } }
  • 7. Static types • Compile time checking • Your IDE will be much more helpful • Encourages encapsulation • Limits your ‘ability’ to write code before thinking • Inferred types greatly reduce boilerplate • … no more “‘NoneType’ object has no attribute…”

  • 8. Rich type system • Monads [Option, Try, Either, …]
 «A monad is a container type together with map and flatMap methods defined on it.» • Functions [Function1, Function2, …] • Generic types [+T, -T] • Higher kinded types
 trait Functor[F[_]] { def map[A, B](fa: F[A])(f: A => B): F[B] } • Structural types
 def setElementText(element : {def setText(text : String)}, text : String)
  • 9. Functions as first-class citizens sealed trait List[A] { def map[A](f: A => A): List[A]
  • 10. Functions as first-class citizens • Higher-order functions (i.e. sum in terms of fold) • Anonymous functions
 (x: Int, y: Int) => x + y • Easily transform collections with map
  • 11. Stress on immutability «[…] there can never be surprises in logic.» – L. Wittgenstein Hopefully, there should never be surprises in code.
  • 12. Stress on immutability object LongestIncreasingSubsequence { def apply(sequence: Seq[Int]): Seq[Int] = { val validSubsequences = iterateAndDropHead(Seq(sequence), sequence) validSubsequences .map(findIncreasingSubsequence) .sortBy(_.length)(Ordering[Int].reverse) .head } @tailrec def iterateAndDropHead(folded: Seq[Seq[Int]], remaining: Seq[Int]): Seq[Seq[Int]] = { remaining match { case head :: Nil => folded case head :: tail => iterateAndDropHead(folded :+ tail, tail) } } def findIncreasingSubsequence(sequence: Seq[Int]): Seq[Int] = { sequence.foldLeft(Seq(sequence.head)) { (acc, el) => if(acc.last < el) acc :+ el else acc } } }
  • 13. Case classes case class Person(firstName: String, lastName: String) val randomGuy = Person("Gabriele", "Alese") randomGuy match { case Person("Gabriele", _) => println("Hello Gabriele!") case Person("Vincent", _) => println("Hello, Vincent!") case _ => println("I've never seen you before") }
  • 14. Case classes • Free accessors (and mutators, if you must) • Free equals() and hashCode() • Free toString() • Free copy() • No need to use new • Free apply and unapply methods 
 on the companion object (see pattern matching)
  • 15. Pattern matching sealed abstract class Expression case class X() extends Expression case class Const(value : Int) extends Expression case class Add(left : Expression, right : Expression) extends Expression case class Mult(left : Expression, right : Expression) extends Expression case class Neg(expr : Expression) extends Expression def eval(expression : Expression, xValue : Int) : Int = expression match { case X() => xValue case Const(cst) => cst case Add(left, right) => eval(left, xValue) + eval(right, xValue) case Mult(left, right) => eval(left, xValue) * eval(right, xValue) case Neg(expr) => - eval(expr, xValue) }
  • 16. Rich collections def sort(xs: Array[Int]): Array[Int] = { if (xs.length <= 1) xs else { val pivot = xs(xs.length / 2) Array.concat( sort(xs filter (pivot >)), xs filter (pivot ==), sort(xs filter (pivot <)) ) } }
  • 17. Rich collections • map • foreach • filter (and filterNot) • zip • find • drop (and dropWhile) • foldLeft (and foldRight)
  • 18. Rich collections def dropWhile[A](l: List[A])(f: A => Boolean): List[A] = l match { case Cons(head, tail) if f(head) => dropWhile(tail)(f) case _ => l } def foldRight[A, B](list: List[A], initial: B)(f: (A, B) => B): B = { list match { case Nil => initial case Cons(head, tail) => f(head, foldRight(tail, initial)(f)) } } def foldLeft[A, B](as: List[A], initial: B)(f: (B, A) => B): B = { as match { case Nil => initial case Cons(head, tail) => foldLeft(tail, f(initial, head))(f) } } def map[A, B](list: List[A])(f: A => B): List[B] = { foldRight(list, Nil: List[B])((a, b) => Cons(f(a), b)) } def filter[A](list: List[A])(f: A => Boolean): List[A] = { foldRight(list, Nil: List[A])((a, b) => if (f(a)) Cons(a, b) else b) } def flatMap[A, B](list: List[A])(f: A => List[B]): List[B] = { concat(map(list)(f)) } }
  • 19. Operator overloading package it.alese.scacchirossi.scacchirossi import it.alese.scacchirossi.scacchirossi.board.{Column, Row} case class Position(column: Column, row: Row) { val x: Int = column.toInt val y: Int = row.toInt def to(toPosition: Position): List[Position] = { Move(this, toPosition).intermediatePositions } def +(x: Int, y: Int) = { val col = if (this.x + x != 0) Column(this.x + x) else this.column val row = if (this.y + y != 0) Row(this.y + y) else this.row new Position(col, row) } … } object Position { def apply(position: String): Position = { require(position.length == 2, "Illegal coordinate string") new Position(Column(position(0)), Row(position(1).asDigit)) } … } package it.alese.scacchirossi.scacchirossi class PositionTest extends WordSpec with Matchers { "A position" should { … "return a new position if summed to an offset" in { Position("A1") + (1,1) shouldEqual Position("B2") Position("A1") + (0,1) shouldEqual Position("A2") } "return a range of contiguous vertical positions" in { Position("A1") to Position("A4") shouldEqual List(Position("A1"), Position("A2"), Position("A3"), Position("A4")) } }
  • 20. Operator overloading • Expressivity 
 (especially combined with infix notation) • Define intuitive operations between types • Pretty powerful DSLs
 (Like ScalaTest)
  • 21. Interoperability with Java libraries package it.alese.emailchecker import java.io.{InputStreamReader, BufferedReader, PrintWriter} import java.net.Socket case class TelnetSession(socket: Socket, input: PrintWriter, output: BufferedReader) { def allowsConnections: Boolean = { Reply(output.readLine).code match { case "220" => true case _ => false } } def send(command: String): String = { input.println(command) output.readLine } def close(): Unit = { send("quit") socket.close() } } object TelnetSession { def apply(host: String): TelnetSession = { val socket = new Socket(host, 25) new TelnetSession( socket, new PrintWriter(socket.getOutputStream, true), new BufferedReader( new InputStreamReader(socket.getInputStream) ) ) } }
  • 22. Interoperability with Java libraries • If you can’t find a Scala library for that, chances are that you’ll find a Java equivalent
 (Good luck with the documentation!) • Appealing for Java programmers
 (or young professionals fresh out of “university Java”) • Stronger community
 (IMHO: many Scala enthusiasts are Java seniors)
  • 23. REPL
  • 24. ???