SlideShare a Scribd company logo
Advanced Scala
April 28th, 2016
OLEG MÜRK, CHIEF ARCHITECT
PLANET OS - APRIL 2016
Advanced Scala
• Advanced features are mostly meant for writing new
• Libraries
• Frameworks
• Domain Specific Languages (DSLs)
• Language extensions

• Application developer mostly needs to know these features
• To efficiently use the libraries
• To efficiently debug issues
• To understand weird typing errors
PLANET OS - APRIL 2016
• Beginner (A1)
• Java-like expressions
• Class, def, val, var
• Closures
• Collections
• For-expressions
• Intermediate (A2)
• Pattern matching
• Trait composition
• (Tail) recursion
• Expert (A3)
• Folds
• Streams
• Actors
• Parser combinators
Scala Levels: Application Developer
PLANET OS - APRIL 2016
• Beginner (Library: L1)
• Type parameters
• Traits
• Lazy vals
• Currying
• Call-by-name • Intermediate (L2)
• Variance
• Existential types
• Self types
• Monads
• Extractors
• Expert (L3)
• Abstract types
• Implicit definitions
• Higher-kinded types
Scala Levels: Library Developer
PLANET OS - APRIL 2016
Higher Order Functions
class List[A] {
def filter(f : A => Boolean) : List[A]
def map[B](f : A => B) : List[B]
def foldLeft[B](z: B)(f: (B, A) => B): B
def foldRight[B](z: B)(f: (A, B) => B): B
}
• Higher order functions take/return functions as arguments
PLANET OS - APRIL 2016
Call-by-Name Parameters
• Call-by-name parameters are not executed at the time of call
def runLater[R](f: => R) = {
new Thread(
new Runnable {
def run { val result = f; … }
}
).start()
}
runLater {
blockingExpensiveFun()
}
PLANET OS - APRIL 2016
Implicit Conversions
• Implicit conversions are implemented with implicit methods
object A2BUtils {
implicit def convertA2B(a:A):B = …
}
import A2BUtils._
val a:A = …
val b:B = a // convertA2B(a)
PLANET OS - APRIL 2016
Extension Methods
• Extensions methods can be implemented with implicit
classes
implicit class DurationInt(private val n: Int) {
def seconds = {
Duration(n.toLong, TimeUnit.SECONDS)
}
}
5.seconds // new DurationInt(5).seconds
PLANET OS - APRIL 2016
Implicit Parameters
• Methods & classes can have implicit parameters
def work(…)(implicit timeout:Duration) = {
…
}
implicit val myDuration = 5.seconds
work(…) // work(…)(myDuration)
PLANET OS - APRIL 2016
Type Classes aka Ad-Hoc Polymorphism
• Type classes can be implemented using implicits
trait Ordering[T] {
def compare(x: T, y: T): Int
}


def min[T](a:T, b:T)(implicit o:Ordering[T]) = …
// Define ordering of Ints
implicit object IntOrdering extends Ordering[Int] {
def compare(x: Int, y: Int) = x - y
}
min(5,6) // min(5,6)(IntOrdering)
PLANET OS - APRIL 2016
Type Classes aka Ad-Hoc Polymorphism
• Type classes can be implemented using implicits
trait Ordering[T] {
def compare(x: T, y: T): Int
}
// These two are equivalent
def min[T](a:T, b:T)(implicit o:Ordering[T]) = …
def min[T:Ordering](a:T, b:T) =
if (implicitly[Ordering[T]].compare(a,b))
a
else
b
}
PLANET OS - APRIL 2016
Futures
• Is a way to asynchronously retrieve the result of a concurrent
operation

def blockingExpensiveFun() : Result = { … }
val resultFuture : Future[Result] =
Future {
blockingExpensiveFun() : Result
}
PLANET OS - APRIL 2016
Execution Context
• Is an abstraction for running Runnable
• It is usually passed around implicitly
implicit val executionContext: ExecutionContext = …

val resultFuture: Future[Result] =
Future {
blockingExpensiveFun()
}//(executionContext)
PLANET OS - APRIL 2016
Awaiting Future Results
• Synchronously await future result with timeout


 import scala.concurrent._
import scala.concurrent.duration._



val resultFuture =
Future {
blockingExpensiveFun()
}
// In most cases You shouldn’t do that :)
val result = Await.result(resutFuture, 15.seconds)
PLANET OS - APRIL 2016
Future Results & Callbacks
• Futures can succeed or fail
val resultFuture: Future[Result] = Future {
blockingExpensiveFun()
}



resultFuture onComplete {

case Success(result) => …
case Failure(throwable) => …
}
PLANET OS - APRIL 2016
Promises
• Promises are used to communicate values between threads

trait Promise[R] {
def future : Future[R]
def success(result:R)
}
PLANET OS - APRIL 2016
Promises
• Promises are used to communicate values between threads

def runLater[R](f: => R) : Future[R] = {
val promise = Promise[R]()
new Thread(new Runnable {
def run { 

val result = f; promise.success(result)
}}).start()
promise.future
}
val resultFuture:Future[R] = runLater{ 

blockingExpensiveFun()
}
PLANET OS - APRIL 2016
Futures Can be Composed: … using Callback Hell
val rateQuote = Future {
connection.getCurrentValue(USD)
}
rateQuote onSuccess { case quote =>
val purchase = Future {
if (isProfitable(quote)) connection.buy(amount, quote)
else throw new Exception("not profitable")
}
purchase onSuccess {
case _ => println("Purchased " + amount + " USD")
}
}
PLANET OS - APRIL 2016
Futures Can be Composed: … or using Monad nirvana
val usdQuote = Future { connection.getCurrentValue(USD) }
val chfQuote = Future { connection.getCurrentValue(CHF) }

val purchase = for {
usd <- usdQuote
chf <- chfQuote
if isProfitable(usd, chf)
} yield connection.buy(amount, chf)

purchase onSuccess {
case _ => println("Purchased " + amount + " CHF")
}
PLANET OS - APRIL 2016
For-Comprehensions are Syntactic Sugar for Monads
val purchase = usdQuote.flatMap {
usd =>
chfQuote
.withFilter(chf => isProfitable(usd, chf))
.map(chf => connection.buy(amount, chf))
}
val purchase = for {
usd <- usdQuote
chf <- chfQuote
if isProfitable(usd, chf)
} yield connection.buy(amount, chf)
PLANET OS - APRIL 2016
For Comprehensions
• For comprehensions work with any Monad
• Examples of monads:
• Seq
• List
• Option
• Either
• Try
• …
PLANET OS - APRIL 2016
For Comprehensions: Seq Example
val list : Seq[(Int,Int)] =
for(
i <- 0 to 100
j <- i to 2*i
if (i*j % 7 == 0)
) yield (i,j)
PLANET OS - APRIL 2016
For Comprehensions: Option Example
sealed trait Option[+T]
case class Some[+T](v:T) extends Option[T]
case object None extends Option[Nothing]
val option : Option[Result] =
for(
i <- mayBeIntermediate() : Option[Intermediate]
r <- mayBeResult(r) : Option[Result]
if check(i, r)
) yield r
PLANET OS - APRIL 2016
For-Comprehensions: Desugaring
genA().map(a => f(a))
for{
a <- genA()
} yield f(a)
PLANET OS - APRIL 2016
For-Comprehensions: Desugaring
genA().flatMap{ a => genB(a).map(b => f(a,b)) }
for{
a <- genA()
b <- gebB(a)
} yield fun(a,b)
PLANET OS - APRIL 2016
For-Comprehensions: Desugaring
genA().flatMap{ a =>
genB(a)
.withFilter{ b => check(a,b) }
.map(b => f(a,b))
)
}
}
for{
a <- genA()
b <- gebB(a)
if check(a,b)
} yield f(a,b)
PLANET OS - APRIL 2016
For Comprehensions & Monads
• For comprehensions work with any Monad
• Examples of monads:
• Seq, List, Option, Either, Try
• Futures
• IO, (Side-)Effects
• Query DSLs (Slick)
• Testing DSLs (ScalaCheck)
PLANET OS - APRIL 2016
Slick - Functional Relational Mapping (FRM)
select c.name, c.price, s.name
from coffees c join suppliers s 

on (c.supID == s.id)
where c.name = "Expresso"
for {
(c, s) <- coffees join suppliers
on (_.supID === _.id)
if c.name === "Espresso"
} yield (c.name, c.price, s.name)
PLANET OS - APRIL 2016
ScalaCheck - Random Testing of Program Properties
val ints = Gen.choose(-100, 100)
def leafs: Gen[Leaf] = for {
x <- ints
} yield Leaf(x)
def nodes: Gen[Node] = for {
left <- trees
right <- trees
} yield Node(left, right)
def trees: Gen[Tree] = Gen.oneOf(leafs, nodes)
PLANET OS - APRIL 2016
Monads, Monads, Monads, Monads!
PLANET OS - APRIL 2016
Monads
All told, a monad in X is just a monoid in the category of
endofunctors of X, with product × replaced by composition of
endofunctors and unit set by the identity endofunctor.
Saunders Mac Lane 

Categories for the Working Mathematician
PLANET OS - APRIL 2016
Monads in Scala
• Monad is a trait parametrized by higher kinded type, eg
• List[ _ ]
• Option[ _ ]
• …
trait Monad[M[_]] {

def unit[A](a: A): M[A]
def flatMap[A, B](m: M[A])(f: A => M[B]): M[B]

}
PLANET OS - APRIL 2016
Monads Laws
• Left identity:

unit(a) >>= f ≡ f(a)
• Right identity: 

m >>= (x => unit(x)) ≡ m
• Associativity: 

(m >>= f) >>= g ≡ m >>= (x => (f(x) >>= g))

• Operator >>= denotes flatMap
PLANET OS - APRIL 2016
List Monad Example
implicit object MonadicList extends Monad[List] {
def unit[A](a:A) : List[A] = List(a)
def flatMap[A,B](l: List[A])

(f: A => List[B]) : List[B] = {
val i:List[List[B]] = l.map(f)
i.flatten
}
}
PLANET OS - APRIL 2016
Option Monad Example
implicit object MonadicOption extends Monad[Option] {

def unit[A](a:A) : Option[A] = Some(a)
def flatMap[A,B](opt : Option[A])

(f: A => Option[B]) : Option[B] = {
opt match {
case Some(a) =>
f(a) : Option[B]
case None =>
None
}
}
}
PLANET OS - APRIL 2016
Advanced Scala Concepts
• Implicits
• Implicit parameters
• Implicit conversions
• Extension methods

• Type-classes aka Adhoc Polymorphism

• For-comprehensions and Monads
PLANET OS - APRIL 2016
Very Advanced Scala Concepts
• Algebra based programming
• Monoids, groups, rings
• Category theory based programming
• Functors, applicative functors, monads, arrows
• Generic programming
• Type-level programming
• Meta-programming
• Scala Reflect
• Scala Meta
PLANET OS - APRIL 2016
Scala Libraries / DSLs
• Async - simpler way to write async code
• Parser Combinators - grammar parsing DSL
• ScalaCheck - random testing of program properties
• Algebird - abstract algebra for scala
• Scalaz/Cats - category theory based programming
• Shapeless - generic programming
• Spire - generic numeric computations
PLANET OS - APRIL 2016
Projects in Scala
• Slick - functional relational mapping for Scala
• Akka - actor-based reactive programming tookit
• Finagle - fault tolerant, protocol-agnostic RPC system
• Spray - high-performance REST/HTTP for Akka
• Play - high velocity web framework for Java and Scala
• Scalding - Scala library to specify MapReduce jobs
• Spark - in-memory cluster computing
• Kafka - publish-subscribe messaging
• Samza - distributed stream processing framework
PLANET OS - APRIL 2016
Scala Advantages
• FP gateway drug for Java developers
• You can treat Scala as Java with prettier syntax
• Runs on JVM, integrates with libraries
• Higher productivity, less lines of code (with type-inference)
• Very suitable for:
• Data processing
• Concurrent/distributed programming
• Libraries/DSLs
• Many errors are caught at compile time (by the type system)
PLANET OS - APRIL 2016
Development in Scala
PLANET OS - APRIL 2016
Scala Downsides: “Modern C++”
• Shoehorning Scala type system into JVM
• Slowish compile-time forces to modularize
• Brittle across Scala and library versions
• Sometimes scary compiler messages
• Compulsion to use all possible Scala features
• Doesn't prevent from creating write-only code
• Libraries/DSLs can have cryptic operators and types
• Optimized inner loops cannot use any advanced features
• Tooling got much better lately
PLANET OS - APRIL 2016
Scala Downsides: Cultural
• Too many different programming styles possible
• Object-oriented
• Basic functional programming
• Advanced functional programming
• Category theory with unicode symbols
• Generic programming
• Type-level programming
• Need to enforce cultural/coding standards in organization
PLANET OS - APRIL 2016
Obligatory Moralistic Slide
49 SEPTEMBER 2015
omurk@planetos.com

More Related Content

What's hot

Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
pramode_ce
 
Workshop presentation hands on r programming
Workshop presentation hands on r programmingWorkshop presentation hands on r programming
Workshop presentation hands on r programming
Nimrita Koul
 
flatMap Oslo presentation slides
flatMap Oslo presentation slidesflatMap Oslo presentation slides
flatMap Oslo presentation slides
Martin Odersky
 
Data translation with SPARQL 1.1
Data translation with SPARQL 1.1Data translation with SPARQL 1.1
Data translation with SPARQL 1.1
andreas_schultz
 

What's hot (20)

R Programming Tutorial for Beginners - -TIB Academy
R Programming Tutorial for Beginners - -TIB AcademyR Programming Tutorial for Beginners - -TIB Academy
R Programming Tutorial for Beginners - -TIB Academy
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
Compilers Are Databases
Compilers Are DatabasesCompilers Are Databases
Compilers Are Databases
 
Java 8
Java 8Java 8
Java 8
 
Scalax
ScalaxScalax
Scalax
 
Scala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationScala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentation
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Oscon keynote: Working hard to keep it simple
Oscon keynote: Working hard to keep it simpleOscon keynote: Working hard to keep it simple
Oscon keynote: Working hard to keep it simple
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Scala eXchange opening
Scala eXchange openingScala eXchange opening
Scala eXchange opening
 
Aggregate Programming in Scala
Aggregate Programming in ScalaAggregate Programming in Scala
Aggregate Programming in Scala
 
Workshop presentation hands on r programming
Workshop presentation hands on r programmingWorkshop presentation hands on r programming
Workshop presentation hands on r programming
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
R programming groundup-basic-section-i
R programming groundup-basic-section-iR programming groundup-basic-section-i
R programming groundup-basic-section-i
 
flatMap Oslo presentation slides
flatMap Oslo presentation slidesflatMap Oslo presentation slides
flatMap Oslo presentation slides
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Introduction to Programming in LISP
Introduction to Programming in LISPIntroduction to Programming in LISP
Introduction to Programming in LISP
 
Data translation with SPARQL 1.1
Data translation with SPARQL 1.1Data translation with SPARQL 1.1
Data translation with SPARQL 1.1
 
Scala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian DragosScala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian Dragos
 

Similar to Advance Scala - Oleg Mürk

Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)
stasimus
 

Similar to Advance Scala - Oleg Mürk (20)

Practical cats
Practical catsPractical cats
Practical cats
 
Frp2016 3
Frp2016 3Frp2016 3
Frp2016 3
 
Advanced Tagless Final - Saying Farewell to Free
Advanced Tagless Final - Saying Farewell to FreeAdvanced Tagless Final - Saying Farewell to Free
Advanced Tagless Final - Saying Farewell to Free
 
Scala. Introduction to FP. Monads
Scala. Introduction to FP. MonadsScala. Introduction to FP. Monads
Scala. Introduction to FP. Monads
 
Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...
 
Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...
 
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
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)
 
Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and Haskell
 
08. haskell Functions
08. haskell Functions08. haskell Functions
08. haskell Functions
 
Free Based DSLs for Distributed Compute Engines
Free Based DSLs for Distributed Compute EnginesFree Based DSLs for Distributed Compute Engines
Free Based DSLs for Distributed Compute Engines
 
Real Time Big Data Management
Real Time Big Data ManagementReal Time Big Data Management
Real Time Big Data Management
 
Big Data Analytics with Scala at SCALA.IO 2013
Big Data Analytics with Scala at SCALA.IO 2013Big Data Analytics with Scala at SCALA.IO 2013
Big Data Analytics with Scala at SCALA.IO 2013
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)
 
Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021
Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021
Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021
 
Monads - Dublin Scala meetup
Monads - Dublin Scala meetupMonads - Dublin Scala meetup
Monads - Dublin Scala meetup
 
Monoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and CatsMonoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and Cats
 
Presentation on use of r statistics
Presentation on use of r statisticsPresentation on use of r statistics
Presentation on use of r statistics
 
Scala collection methods flatMap and flatten are more powerful than monadic f...
Scala collection methods flatMap and flatten are more powerful than monadic f...Scala collection methods flatMap and flatten are more powerful than monadic f...
Scala collection methods flatMap and flatten are more powerful than monadic f...
 

Recently uploaded

Recently uploaded (20)

Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
In-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsIn-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT Professionals
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
 
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...
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through Observability
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
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...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 
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
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 

Advance Scala - Oleg Mürk

  • 1. Advanced Scala April 28th, 2016 OLEG MÜRK, CHIEF ARCHITECT
  • 2. PLANET OS - APRIL 2016 Advanced Scala • Advanced features are mostly meant for writing new • Libraries • Frameworks • Domain Specific Languages (DSLs) • Language extensions
 • Application developer mostly needs to know these features • To efficiently use the libraries • To efficiently debug issues • To understand weird typing errors
  • 3. PLANET OS - APRIL 2016 • Beginner (A1) • Java-like expressions • Class, def, val, var • Closures • Collections • For-expressions • Intermediate (A2) • Pattern matching • Trait composition • (Tail) recursion • Expert (A3) • Folds • Streams • Actors • Parser combinators Scala Levels: Application Developer
  • 4. PLANET OS - APRIL 2016 • Beginner (Library: L1) • Type parameters • Traits • Lazy vals • Currying • Call-by-name • Intermediate (L2) • Variance • Existential types • Self types • Monads • Extractors • Expert (L3) • Abstract types • Implicit definitions • Higher-kinded types Scala Levels: Library Developer
  • 5. PLANET OS - APRIL 2016 Higher Order Functions class List[A] { def filter(f : A => Boolean) : List[A] def map[B](f : A => B) : List[B] def foldLeft[B](z: B)(f: (B, A) => B): B def foldRight[B](z: B)(f: (A, B) => B): B } • Higher order functions take/return functions as arguments
  • 6. PLANET OS - APRIL 2016 Call-by-Name Parameters • Call-by-name parameters are not executed at the time of call def runLater[R](f: => R) = { new Thread( new Runnable { def run { val result = f; … } } ).start() } runLater { blockingExpensiveFun() }
  • 7. PLANET OS - APRIL 2016 Implicit Conversions • Implicit conversions are implemented with implicit methods object A2BUtils { implicit def convertA2B(a:A):B = … } import A2BUtils._ val a:A = … val b:B = a // convertA2B(a)
  • 8. PLANET OS - APRIL 2016 Extension Methods • Extensions methods can be implemented with implicit classes implicit class DurationInt(private val n: Int) { def seconds = { Duration(n.toLong, TimeUnit.SECONDS) } } 5.seconds // new DurationInt(5).seconds
  • 9. PLANET OS - APRIL 2016 Implicit Parameters • Methods & classes can have implicit parameters def work(…)(implicit timeout:Duration) = { … } implicit val myDuration = 5.seconds work(…) // work(…)(myDuration)
  • 10. PLANET OS - APRIL 2016 Type Classes aka Ad-Hoc Polymorphism • Type classes can be implemented using implicits trait Ordering[T] { def compare(x: T, y: T): Int } 
 def min[T](a:T, b:T)(implicit o:Ordering[T]) = … // Define ordering of Ints implicit object IntOrdering extends Ordering[Int] { def compare(x: Int, y: Int) = x - y } min(5,6) // min(5,6)(IntOrdering)
  • 11. PLANET OS - APRIL 2016 Type Classes aka Ad-Hoc Polymorphism • Type classes can be implemented using implicits trait Ordering[T] { def compare(x: T, y: T): Int } // These two are equivalent def min[T](a:T, b:T)(implicit o:Ordering[T]) = … def min[T:Ordering](a:T, b:T) = if (implicitly[Ordering[T]].compare(a,b)) a else b }
  • 12. PLANET OS - APRIL 2016 Futures • Is a way to asynchronously retrieve the result of a concurrent operation
 def blockingExpensiveFun() : Result = { … } val resultFuture : Future[Result] = Future { blockingExpensiveFun() : Result }
  • 13. PLANET OS - APRIL 2016 Execution Context • Is an abstraction for running Runnable • It is usually passed around implicitly implicit val executionContext: ExecutionContext = …
 val resultFuture: Future[Result] = Future { blockingExpensiveFun() }//(executionContext)
  • 14. PLANET OS - APRIL 2016 Awaiting Future Results • Synchronously await future result with timeout
 
 import scala.concurrent._ import scala.concurrent.duration._
 
 val resultFuture = Future { blockingExpensiveFun() } // In most cases You shouldn’t do that :) val result = Await.result(resutFuture, 15.seconds)
  • 15. PLANET OS - APRIL 2016 Future Results & Callbacks • Futures can succeed or fail val resultFuture: Future[Result] = Future { blockingExpensiveFun() }
 
 resultFuture onComplete {
 case Success(result) => … case Failure(throwable) => … }
  • 16. PLANET OS - APRIL 2016 Promises • Promises are used to communicate values between threads
 trait Promise[R] { def future : Future[R] def success(result:R) }
  • 17. PLANET OS - APRIL 2016 Promises • Promises are used to communicate values between threads
 def runLater[R](f: => R) : Future[R] = { val promise = Promise[R]() new Thread(new Runnable { def run { 
 val result = f; promise.success(result) }}).start() promise.future } val resultFuture:Future[R] = runLater{ 
 blockingExpensiveFun() }
  • 18. PLANET OS - APRIL 2016 Futures Can be Composed: … using Callback Hell val rateQuote = Future { connection.getCurrentValue(USD) } rateQuote onSuccess { case quote => val purchase = Future { if (isProfitable(quote)) connection.buy(amount, quote) else throw new Exception("not profitable") } purchase onSuccess { case _ => println("Purchased " + amount + " USD") } }
  • 19. PLANET OS - APRIL 2016 Futures Can be Composed: … or using Monad nirvana val usdQuote = Future { connection.getCurrentValue(USD) } val chfQuote = Future { connection.getCurrentValue(CHF) }
 val purchase = for { usd <- usdQuote chf <- chfQuote if isProfitable(usd, chf) } yield connection.buy(amount, chf)
 purchase onSuccess { case _ => println("Purchased " + amount + " CHF") }
  • 20. PLANET OS - APRIL 2016 For-Comprehensions are Syntactic Sugar for Monads val purchase = usdQuote.flatMap { usd => chfQuote .withFilter(chf => isProfitable(usd, chf)) .map(chf => connection.buy(amount, chf)) } val purchase = for { usd <- usdQuote chf <- chfQuote if isProfitable(usd, chf) } yield connection.buy(amount, chf)
  • 21. PLANET OS - APRIL 2016 For Comprehensions • For comprehensions work with any Monad • Examples of monads: • Seq • List • Option • Either • Try • …
  • 22. PLANET OS - APRIL 2016 For Comprehensions: Seq Example val list : Seq[(Int,Int)] = for( i <- 0 to 100 j <- i to 2*i if (i*j % 7 == 0) ) yield (i,j)
  • 23. PLANET OS - APRIL 2016 For Comprehensions: Option Example sealed trait Option[+T] case class Some[+T](v:T) extends Option[T] case object None extends Option[Nothing] val option : Option[Result] = for( i <- mayBeIntermediate() : Option[Intermediate] r <- mayBeResult(r) : Option[Result] if check(i, r) ) yield r
  • 24. PLANET OS - APRIL 2016 For-Comprehensions: Desugaring genA().map(a => f(a)) for{ a <- genA() } yield f(a)
  • 25. PLANET OS - APRIL 2016 For-Comprehensions: Desugaring genA().flatMap{ a => genB(a).map(b => f(a,b)) } for{ a <- genA() b <- gebB(a) } yield fun(a,b)
  • 26. PLANET OS - APRIL 2016 For-Comprehensions: Desugaring genA().flatMap{ a => genB(a) .withFilter{ b => check(a,b) } .map(b => f(a,b)) ) } } for{ a <- genA() b <- gebB(a) if check(a,b) } yield f(a,b)
  • 27. PLANET OS - APRIL 2016 For Comprehensions & Monads • For comprehensions work with any Monad • Examples of monads: • Seq, List, Option, Either, Try • Futures • IO, (Side-)Effects • Query DSLs (Slick) • Testing DSLs (ScalaCheck)
  • 28. PLANET OS - APRIL 2016 Slick - Functional Relational Mapping (FRM) select c.name, c.price, s.name from coffees c join suppliers s 
 on (c.supID == s.id) where c.name = "Expresso" for { (c, s) <- coffees join suppliers on (_.supID === _.id) if c.name === "Espresso" } yield (c.name, c.price, s.name)
  • 29. PLANET OS - APRIL 2016 ScalaCheck - Random Testing of Program Properties val ints = Gen.choose(-100, 100) def leafs: Gen[Leaf] = for { x <- ints } yield Leaf(x) def nodes: Gen[Node] = for { left <- trees right <- trees } yield Node(left, right) def trees: Gen[Tree] = Gen.oneOf(leafs, nodes)
  • 30. PLANET OS - APRIL 2016 Monads, Monads, Monads, Monads!
  • 31. PLANET OS - APRIL 2016 Monads All told, a monad in X is just a monoid in the category of endofunctors of X, with product × replaced by composition of endofunctors and unit set by the identity endofunctor. Saunders Mac Lane 
 Categories for the Working Mathematician
  • 32. PLANET OS - APRIL 2016 Monads in Scala • Monad is a trait parametrized by higher kinded type, eg • List[ _ ] • Option[ _ ] • … trait Monad[M[_]] {
 def unit[A](a: A): M[A] def flatMap[A, B](m: M[A])(f: A => M[B]): M[B]
 }
  • 33. PLANET OS - APRIL 2016 Monads Laws • Left identity:
 unit(a) >>= f ≡ f(a) • Right identity: 
 m >>= (x => unit(x)) ≡ m • Associativity: 
 (m >>= f) >>= g ≡ m >>= (x => (f(x) >>= g))
 • Operator >>= denotes flatMap
  • 34. PLANET OS - APRIL 2016 List Monad Example implicit object MonadicList extends Monad[List] { def unit[A](a:A) : List[A] = List(a) def flatMap[A,B](l: List[A])
 (f: A => List[B]) : List[B] = { val i:List[List[B]] = l.map(f) i.flatten } }
  • 35. PLANET OS - APRIL 2016 Option Monad Example implicit object MonadicOption extends Monad[Option] {
 def unit[A](a:A) : Option[A] = Some(a) def flatMap[A,B](opt : Option[A])
 (f: A => Option[B]) : Option[B] = { opt match { case Some(a) => f(a) : Option[B] case None => None } } }
  • 36. PLANET OS - APRIL 2016 Advanced Scala Concepts • Implicits • Implicit parameters • Implicit conversions • Extension methods
 • Type-classes aka Adhoc Polymorphism
 • For-comprehensions and Monads
  • 37. PLANET OS - APRIL 2016 Very Advanced Scala Concepts • Algebra based programming • Monoids, groups, rings • Category theory based programming • Functors, applicative functors, monads, arrows • Generic programming • Type-level programming • Meta-programming • Scala Reflect • Scala Meta
  • 38. PLANET OS - APRIL 2016 Scala Libraries / DSLs • Async - simpler way to write async code • Parser Combinators - grammar parsing DSL • ScalaCheck - random testing of program properties • Algebird - abstract algebra for scala • Scalaz/Cats - category theory based programming • Shapeless - generic programming • Spire - generic numeric computations
  • 39. PLANET OS - APRIL 2016 Projects in Scala • Slick - functional relational mapping for Scala • Akka - actor-based reactive programming tookit • Finagle - fault tolerant, protocol-agnostic RPC system • Spray - high-performance REST/HTTP for Akka • Play - high velocity web framework for Java and Scala • Scalding - Scala library to specify MapReduce jobs • Spark - in-memory cluster computing • Kafka - publish-subscribe messaging • Samza - distributed stream processing framework
  • 40. PLANET OS - APRIL 2016 Scala Advantages • FP gateway drug for Java developers • You can treat Scala as Java with prettier syntax • Runs on JVM, integrates with libraries • Higher productivity, less lines of code (with type-inference) • Very suitable for: • Data processing • Concurrent/distributed programming • Libraries/DSLs • Many errors are caught at compile time (by the type system)
  • 41. PLANET OS - APRIL 2016 Development in Scala
  • 42. PLANET OS - APRIL 2016 Scala Downsides: “Modern C++” • Shoehorning Scala type system into JVM • Slowish compile-time forces to modularize • Brittle across Scala and library versions • Sometimes scary compiler messages • Compulsion to use all possible Scala features • Doesn't prevent from creating write-only code • Libraries/DSLs can have cryptic operators and types • Optimized inner loops cannot use any advanced features • Tooling got much better lately
  • 43. PLANET OS - APRIL 2016 Scala Downsides: Cultural • Too many different programming styles possible • Object-oriented • Basic functional programming • Advanced functional programming • Category theory with unicode symbols • Generic programming • Type-level programming • Need to enforce cultural/coding standards in organization
  • 44. PLANET OS - APRIL 2016 Obligatory Moralistic Slide