SlideShare a Scribd company logo
Introduction to Scala and HOF’s
Who am I?
@raulraja
47deg.com
raulraja.com
Scala, Java, Objective-C
http://www.quora.com/Startups/What-startups-or-tech-companies-are-using-Scala

L
VE
N
O

ER
YA
M

W
AR
E

VM

TU

M

BL
R

TE
IT
TW

B
O
KM
ST
AC

M
IC
ES

SE

M

R

K
IL
M
TH
BE
R
EM

RE

M

O
RA

G

Q
U

N
VI
LI

E

SO
C

KE
LI
N

IA
L

DI
N

O
KL

C

H
SB

M
AR
H

E-

BO

AO
L

X

O

N

U

T

Y

WHO USES SCALA?
/47 DEGREES AND...
SCALA ECOSYSTEM
/JUST A FEW...
LEARN SCALA
/BOOKS
LEARN SCALA
/FREE ONLINE COURSES
WORLD DOMINATION IS UNDERWAY
/GET ON THE WAGON BEFORE ITS TOO LATE
SCALA FEATURES
/JUST A FEW...
IMMUTABILITY EMPHASIS

FUNCTIONAL

OOP

Emphasis on immutable
data structures.
Transformations and
copies vs state

High Order functions and
great support for map,
flatmap, tabulate, filter,
foreach...

Traits, classes, case
classes, object...

ACTORS

MIXINS

IDIOMATIC

Built in support for this
high concurrency pattern

Attach behaviors at
runtime.
new Foo with Other

Flexible syntax, create
constructs, infix support,
everything is a value
val test = if(...)
val collection = for(...)
WHY LEARN SCALA?
/A MODERN LANGUAGE FOR MASSIVE
CONCURRENT APPLICATIONS IN THE CLOUD
SHOW ME THE CODE!!!
IMMUTABILITY

In Java we tend to use Mutable structures
that need synchronization
JAVA
List<Integer> even = new ArrayList<Integer>();
for (String num : numbersAsStrings) {
int parsedInt = Integer.parseInt(num);
if (parsedInt % 2 == 0) {
ints.add(parsedInt);
}
}

In Scala we transform values into new values
SCALA
val ints = for (num <- numbersAsStrings; if num.toInt % 2 == 0) yield num.toInt

No need to synchronize in structures which
state is never modified
FUNCTIONAL

In Scala everything returns a value
scala> val myInt = 1
myInt: Int = 1
scala> def myFunction = "I don't need a return"
myFunction: String
scala> val result = for (n <- 0 to 10) yield n
result: scala.collection.immutable.IndexedSeq[Int] = Vector(0, 1, 2, 3, 4, 5, 6, 7, 8,
9, 10)
scala> val ifAreValues2 = if (true) "test"
ifAreValues2: Any = test
scala> val ifAreValues3 = if (true) "test" else "test2"
ifAreValues3: String = test

Functional style encourages to pipe the
results of functions and operations Vs
Imperative style
Iterator.continually(Option(queue.poll(1, TimeUnit.SECONDS))).takeWhile(_ => running)
foreach { msg => write(msg) }
OOP

In Scala everything is an Object and
supports a richer object model than Java
( multiple inheritance? :) )
Traits
trait Similarity {
def isSimilar(x: Any): Boolean
def isNotSimilar(x: Any): Boolean = !isSimilar(x)
}
Classes
class Point(xc: Int, yc: Int) extends Similarity {
var x: Int = xc
var y: Int = yc
def isSimilar(obj: Any) =
obj.isInstanceOf[Point] &&
obj.asInstanceOf[Point].x == x
}
Case Classes
case class Point(xc: Int, yc: Int) extends Similarity {
def isSimilar(obj: Any) = obj.isInstanceOf[Point] && obj.asInstanceOf[Point].x == x
}
Objects (singletons)
object TraitsTest {
val p1 = Point(2, 3)
val p2 = Point(2, 4)
val p3 = Point(3, 3)
println(p1.isNotSimilar(p2))
println(p1.isNotSimilar(p3))
println(p1.isNotSimilar(2))
}
ACTORS

Use actors for a high concurrent fault
tolerant distributed messaging system
/** invoke your army **/
val emailServiceActor = Akka.system.actorOf(
Props[EmailServiceActor].withRouter(
SmallestMailboxRouter(nrOfInstances = 50)
), name = "emailService"
)
/** send him to war **/
emailServiceActor ! emailMessage
/** this is the guy overseeing everything in the pentagon **/
class EmailServiceActor extends Actor{
override val supervisorStrategy =
OneForOneStrategy(maxNrOfRetries = 10) {
case emailException: EmailException => Restart
case unknownCase: Any => Stop
}
def receive = {
case message: Any => context.actorOf(Props[EmailServiceWorker]) ! message
}
}
/** And this one is the one in the field **/
class EmailServiceWorker extends Actor{
/** And this one is the one in the field **/
private var emailMessage: Option[EmailMessage] = None
def receive = {
case Some(email): EmailMessage => {
email.deliveryAttempts = email.deliveryAttempts + 1
email sendEmailSync()
}
case unexpectedMessage: Any => throw new Exception("can't handle %s" format(unexpectedMessage))
}

}

override def preRestart(reason: Throwable, message: Option[Any]) {
context.system.scheduler.scheduleOnce(emailMessage.get.retryOn, self, emailMessage.get)
}
MIXINS

What can fish do?

trait Swimmer { def swim = println("I'm swimming")}
class Fish extends Swimmer ...
trait Walker { def walk = println("I'm walking")}
val mudSkipper = new Fish() with Walker
mudSkipper.walk()
IDIOMATIC

DSL capable and idiomatic syntax
http://stackoverflow.com/questions/3186783/interesting-dsls-implemented-in-scala
/** Poll every second and stream messages **/
Iterator.continually(
Option(queue
.poll(1, TimeUnit.SECONDS)))
.takeWhile(_ => running) foreach { msg => write(msg) }
/** TDD and BDD ? **/
test("pop is invoked on an empty stack") {
val emptyStack = new Stack[String]
evaluating { emptyStack.pop() } should produce [NoSuchElementException]
emptyStack should be ('empty)
}
/** DB manipulation ? **/
def songCountByArtistId: Query[GroupWithMeasures[Long,Long]] =
from(artists, songs)((a,s) =>
where(a.id === s.artistId)
groupBy(a.id)
compute(count)
)
/** Json manipulation ? **/
("person" ->
("name" -> "Joe") ~
("age" -> 35) ~
("spouse" ->
("person" ->
("name" -> "Marilyn") ~
("age" -> 33)
)
)
)
/** Xml manipulation ? **/
val page =
<html>
<head>
<title>Hello XHTML world</title>
</head>
<body>
<h1>Hello world</h1>
</body>
</html>;
1. HOF Higher Order Functions
A function that takes a function as argument
or returns another function
e.g. map & filter
map transforms data
map sadness to happiness
:( :( :(

=> :) :) :)
map sadness to happiness - JAVA
public List<String> mapSadnessToHappiness (List<String> sadness) {
List<String> happiness = new ArrayList<String>(sadness.size());
for (int i = 0; i < sadness.size(); i++) {
String sadFace = sadness.get(i);
String happyFace = sadFace.replace('(', ')');
happiness.add(happyFace);
}
return happiness;
}
List<String> sadness = Arrays.asList(":(", ":(", ":(");
List<String> happiness = mapSadnessToHappiness(sadness);
map sadness to happiness - Scala
List(":(", ":(", ":(").map(face => face.replace('(', ')'))
map sadness to happiness - Scala
List(":(", ":(", ":(").map(_.replace('(', ')'))
filter remove the unwanted
filter sadness keeping happiness
:) :) :(

=> :) :)
filter sadness keeping happiness
List(":)", ":)", ":(").filter(_.contains(":)"))
Idiomatic Transformations
Count char occurrences on a String - JAVA
public static int countCharOccurrences(String haystack, char needle) {
int count = 0;
for (int i = 0; i < haystack.length(); i++) {
if (haystack.charAt(i) == needle) {
count++;
}
}
return count;
}
public static Map<Character, Integer> toCharOccurrenceMap(String haystack) {
Map<Character, Integer> map = new HashMap<Character, Integer>();
if (haystack != null) {
for (int i = 0; i < haystack.length(); i++) {
char character = haystack.charAt(i);
int count = countCharOccurrences(haystack, character);
map.put(character, count);
}
}
return map;
}
toCharOccurrenceMap("betabeers");
Idiomatic Transformations
Count char occurrences on a String
"betabeers" groupBy identity mapValues (_.size)
Key differentiator
Higher Order Functions help with most Collection problems that you usually solve by
looping over and manually creating intermediate containers.
Transformed results stay immutable and thread safe.
No need to reinvent the wheel.
Code becomes readable and idiomatic
"betabeers" groupBy identity mapValues (_.size)
Other Powerful HOF’s examples
Sum
(1 to 1000).reduceLeft( _ + _ )
(1 to 1000).sum

Partition filter
val (passed, failed) = List(49, 58, 88, 90) partition ( _ > 60 )

min
List(14, 35, -7, 46, 98).min

max
List(14, 35, -7, 46, 98).max

Imperative iteration
(1 to 10) foreach (println)

Parallel Collections
(1 to 10).par foreach(_ => println(Thread.currentThread.getName))
Become a Scala Master
For comprehensions
Case Classes
Futures
Options
Traits
Either
Pattern Matching
Monads
Actors
DSL’s
...

More Related Content

What's hot

1.2 Scala Basics
1.2 Scala Basics1.2 Scala Basics
1.2 Scala Basicsretronym
 
A bit about Scala
A bit about ScalaA bit about Scala
A bit about Scala
Vladimir Parfinenko
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Meetu Maltiar
 
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
 
Swift Rocks #2: Going functional
Swift Rocks #2: Going functionalSwift Rocks #2: Going functional
Swift Rocks #2: Going functional
Hackraft
 
Scala for Jedi
Scala for JediScala for Jedi
Scala for Jedi
Vladimir Parfinenko
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risks
SeniorDevOnly
 
Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2
Kirill Rozov
 
Brief tour of psp-std
Brief tour of psp-stdBrief tour of psp-std
Brief tour of psp-std
Paul Phillips
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Development
vito jeng
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
Łukasz Bałamut
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
Maxim Novak
 
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
JDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation streamJDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation stream
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
Ruslan Shevchenko
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in Scala
Shai Yallin
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
Christian Baranowski
 
An Introduction to Scala (2014)
An Introduction to Scala (2014)An Introduction to Scala (2014)
An Introduction to Scala (2014)
William Narmontas
 
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Sanjeev_Knoldus
 
All about scala
All about scalaAll about scala
All about scala
Yardena Meymann
 

What's hot (20)

1.2 Scala Basics
1.2 Scala Basics1.2 Scala Basics
1.2 Scala Basics
 
A bit about Scala
A bit about ScalaA bit about Scala
A bit about Scala
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Scala collections
Scala collectionsScala collections
Scala collections
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
Swift Rocks #2: Going functional
Swift Rocks #2: Going functionalSwift Rocks #2: Going functional
Swift Rocks #2: Going functional
 
Scala for Jedi
Scala for JediScala for Jedi
Scala for Jedi
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risks
 
Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2
 
Brief tour of psp-std
Brief tour of psp-stdBrief tour of psp-std
Brief tour of psp-std
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Development
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
 
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
JDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation streamJDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation stream
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in Scala
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
An Introduction to Scala (2014)
An Introduction to Scala (2014)An Introduction to Scala (2014)
An Introduction to Scala (2014)
 
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
 
All about scala
All about scalaAll about scala
All about scala
 

Similar to 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?Tomasz Wrobel
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
league
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
Razvan Cojocaru
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Aleksandar Prokopec
 
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
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
Jesper Kamstrup Linnet
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
Stuart Roebuck
 
Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat Sheet
Saeid Zebardast
 
Pragmatic Real-World Scala
Pragmatic Real-World ScalaPragmatic Real-World Scala
Pragmatic Real-World Scalaparag978978
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
Jonas Bonér
 
Intro to scala
Intro to scalaIntro to scala
Intro to scalaJoe Zulli
 
Scala - en bedre Java?
Scala - en bedre Java?Scala - en bedre Java?
Scala - en bedre Java?
Jesper Kamstrup Linnet
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scalashinolajla
 
Meet scala
Meet scalaMeet scala
Meet scala
Wojciech Pituła
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
Derek Chen-Becker
 

Similar to Introduction to Scala (20)

(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?
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
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
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat Sheet
 
Pragmatic Real-World Scala
Pragmatic Real-World ScalaPragmatic Real-World Scala
Pragmatic Real-World Scala
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Intro to scala
Intro to scalaIntro to scala
Intro to scala
 
Scala - en bedre Java?
Scala - en bedre Java?Scala - en bedre Java?
Scala - en bedre Java?
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 
Meet scala
Meet scalaMeet scala
Meet scala
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
 

Recently uploaded

GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
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
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 

Recently uploaded (20)

GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
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
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 

Introduction to Scala

  • 1. Introduction to Scala and HOF’s
  • 7. WORLD DOMINATION IS UNDERWAY /GET ON THE WAGON BEFORE ITS TOO LATE
  • 8. SCALA FEATURES /JUST A FEW... IMMUTABILITY EMPHASIS FUNCTIONAL OOP Emphasis on immutable data structures. Transformations and copies vs state High Order functions and great support for map, flatmap, tabulate, filter, foreach... Traits, classes, case classes, object... ACTORS MIXINS IDIOMATIC Built in support for this high concurrency pattern Attach behaviors at runtime. new Foo with Other Flexible syntax, create constructs, infix support, everything is a value val test = if(...) val collection = for(...)
  • 9. WHY LEARN SCALA? /A MODERN LANGUAGE FOR MASSIVE CONCURRENT APPLICATIONS IN THE CLOUD
  • 10. SHOW ME THE CODE!!!
  • 11. IMMUTABILITY In Java we tend to use Mutable structures that need synchronization JAVA List<Integer> even = new ArrayList<Integer>(); for (String num : numbersAsStrings) { int parsedInt = Integer.parseInt(num); if (parsedInt % 2 == 0) { ints.add(parsedInt); } } In Scala we transform values into new values SCALA val ints = for (num <- numbersAsStrings; if num.toInt % 2 == 0) yield num.toInt No need to synchronize in structures which state is never modified
  • 12. FUNCTIONAL In Scala everything returns a value scala> val myInt = 1 myInt: Int = 1 scala> def myFunction = "I don't need a return" myFunction: String scala> val result = for (n <- 0 to 10) yield n result: scala.collection.immutable.IndexedSeq[Int] = Vector(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala> val ifAreValues2 = if (true) "test" ifAreValues2: Any = test scala> val ifAreValues3 = if (true) "test" else "test2" ifAreValues3: String = test Functional style encourages to pipe the results of functions and operations Vs Imperative style Iterator.continually(Option(queue.poll(1, TimeUnit.SECONDS))).takeWhile(_ => running) foreach { msg => write(msg) }
  • 13. OOP In Scala everything is an Object and supports a richer object model than Java ( multiple inheritance? :) ) Traits trait Similarity { def isSimilar(x: Any): Boolean def isNotSimilar(x: Any): Boolean = !isSimilar(x) } Classes class Point(xc: Int, yc: Int) extends Similarity { var x: Int = xc var y: Int = yc def isSimilar(obj: Any) = obj.isInstanceOf[Point] && obj.asInstanceOf[Point].x == x } Case Classes case class Point(xc: Int, yc: Int) extends Similarity { def isSimilar(obj: Any) = obj.isInstanceOf[Point] && obj.asInstanceOf[Point].x == x } Objects (singletons) object TraitsTest { val p1 = Point(2, 3) val p2 = Point(2, 4) val p3 = Point(3, 3) println(p1.isNotSimilar(p2)) println(p1.isNotSimilar(p3)) println(p1.isNotSimilar(2)) }
  • 14. ACTORS Use actors for a high concurrent fault tolerant distributed messaging system /** invoke your army **/ val emailServiceActor = Akka.system.actorOf( Props[EmailServiceActor].withRouter( SmallestMailboxRouter(nrOfInstances = 50) ), name = "emailService" ) /** send him to war **/ emailServiceActor ! emailMessage /** this is the guy overseeing everything in the pentagon **/ class EmailServiceActor extends Actor{ override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 10) { case emailException: EmailException => Restart case unknownCase: Any => Stop } def receive = { case message: Any => context.actorOf(Props[EmailServiceWorker]) ! message } } /** And this one is the one in the field **/ class EmailServiceWorker extends Actor{ /** And this one is the one in the field **/ private var emailMessage: Option[EmailMessage] = None def receive = { case Some(email): EmailMessage => { email.deliveryAttempts = email.deliveryAttempts + 1 email sendEmailSync() } case unexpectedMessage: Any => throw new Exception("can't handle %s" format(unexpectedMessage)) } } override def preRestart(reason: Throwable, message: Option[Any]) { context.system.scheduler.scheduleOnce(emailMessage.get.retryOn, self, emailMessage.get) }
  • 15. MIXINS What can fish do? trait Swimmer { def swim = println("I'm swimming")} class Fish extends Swimmer ... trait Walker { def walk = println("I'm walking")} val mudSkipper = new Fish() with Walker mudSkipper.walk()
  • 16. IDIOMATIC DSL capable and idiomatic syntax http://stackoverflow.com/questions/3186783/interesting-dsls-implemented-in-scala /** Poll every second and stream messages **/ Iterator.continually( Option(queue .poll(1, TimeUnit.SECONDS))) .takeWhile(_ => running) foreach { msg => write(msg) } /** TDD and BDD ? **/ test("pop is invoked on an empty stack") { val emptyStack = new Stack[String] evaluating { emptyStack.pop() } should produce [NoSuchElementException] emptyStack should be ('empty) } /** DB manipulation ? **/ def songCountByArtistId: Query[GroupWithMeasures[Long,Long]] = from(artists, songs)((a,s) => where(a.id === s.artistId) groupBy(a.id) compute(count) ) /** Json manipulation ? **/ ("person" -> ("name" -> "Joe") ~ ("age" -> 35) ~ ("spouse" -> ("person" -> ("name" -> "Marilyn") ~ ("age" -> 33) ) ) ) /** Xml manipulation ? **/ val page = <html> <head> <title>Hello XHTML world</title> </head> <body> <h1>Hello world</h1> </body> </html>;
  • 17. 1. HOF Higher Order Functions A function that takes a function as argument or returns another function e.g. map & filter
  • 19. map sadness to happiness :( :( :( => :) :) :)
  • 20. map sadness to happiness - JAVA public List<String> mapSadnessToHappiness (List<String> sadness) { List<String> happiness = new ArrayList<String>(sadness.size()); for (int i = 0; i < sadness.size(); i++) { String sadFace = sadness.get(i); String happyFace = sadFace.replace('(', ')'); happiness.add(happyFace); } return happiness; } List<String> sadness = Arrays.asList(":(", ":(", ":("); List<String> happiness = mapSadnessToHappiness(sadness);
  • 21. map sadness to happiness - Scala List(":(", ":(", ":(").map(face => face.replace('(', ')'))
  • 22. map sadness to happiness - Scala List(":(", ":(", ":(").map(_.replace('(', ')'))
  • 23. filter remove the unwanted
  • 24. filter sadness keeping happiness :) :) :( => :) :)
  • 25. filter sadness keeping happiness List(":)", ":)", ":(").filter(_.contains(":)"))
  • 26. Idiomatic Transformations Count char occurrences on a String - JAVA public static int countCharOccurrences(String haystack, char needle) { int count = 0; for (int i = 0; i < haystack.length(); i++) { if (haystack.charAt(i) == needle) { count++; } } return count; } public static Map<Character, Integer> toCharOccurrenceMap(String haystack) { Map<Character, Integer> map = new HashMap<Character, Integer>(); if (haystack != null) { for (int i = 0; i < haystack.length(); i++) { char character = haystack.charAt(i); int count = countCharOccurrences(haystack, character); map.put(character, count); } } return map; } toCharOccurrenceMap("betabeers");
  • 27. Idiomatic Transformations Count char occurrences on a String "betabeers" groupBy identity mapValues (_.size)
  • 28. Key differentiator Higher Order Functions help with most Collection problems that you usually solve by looping over and manually creating intermediate containers. Transformed results stay immutable and thread safe. No need to reinvent the wheel. Code becomes readable and idiomatic "betabeers" groupBy identity mapValues (_.size)
  • 29. Other Powerful HOF’s examples Sum (1 to 1000).reduceLeft( _ + _ ) (1 to 1000).sum Partition filter val (passed, failed) = List(49, 58, 88, 90) partition ( _ > 60 ) min List(14, 35, -7, 46, 98).min max List(14, 35, -7, 46, 98).max Imperative iteration (1 to 10) foreach (println) Parallel Collections (1 to 10).par foreach(_ => println(Thread.currentThread.getName))
  • 30. Become a Scala Master For comprehensions Case Classes Futures Options Traits Either Pattern Matching Monads Actors DSL’s ...