SlideShare une entreprise Scribd logo
1  sur  13
Télécharger pour lire hors ligne
SCALA TRAINING
the language matters
1
Agenda
• Function
• Implicit
• Monad
• Actor
Language features - functions
• high order function
3
Language - Implicit
• implicit convention
Language - Implicit
val personJson = """{ "name": "Jason" }”""
val r1 = httpClient(Request(
GET, new URI("http://api.rest.org/person/"),
Map(), None))
val r2 = httpClient(Request(
POST, new URI("http://api.rest.org/person/"),
Map(), Some(personJson)))
val id = r2.headers(“X-Person-Id").head
val r3 = httpClient(Request(
GET, new URI("http://api.rest.org/person/" + id),
Map(), None))
val r4 = httpClient(Request(
GET, new URI("http://api.rest.org/person/"),
Map(), None))
val r5 = httpClient(Request(
DELETE, new URI("http://api.rest.org/person/" + id),
Map(), None))
Language - Implicit
using(_ url "http://api.rest.org") { implicit rb =>
GET / "person"
asserting (StatusCode === Status.OK, BodyAsPersonList === EmptyList)
val id = POST / "person" body personJson
asserting (StatusCode === Status.Created)
returning (header(“X-Person-Id"))
GET / "person" / id
asserting (StatusCode === Status.OK, BodyAsPerson === Jason)
GET / "person"
asserting (StatusCode === Status.OK, BodyAsPersonList === Seq(Jason))
DELETE / "person" / id
asserting (StatusCode === Status.OK)
GET / "person"
asserting (StatusCode === Status.OK, BodyAsPersonList === EmptyList)
}
Language Feature - Monad
sealed abstract class Try[+T]
case class Success[+T](value: T)
case class Failure[+T](exception: Throwable)
case abstract class Option[T]
case class Some[T]
case object None extends Option[Nothing] {//…}
Language Feature - Monad
//in User
def findById(id: Long):Try[User] = {
//Success(user) or Failure(e)
}
//in Post
def findByUser(user: User):Try[List[Post]] = {
//Success(posts)or Failure(e)
}
val posts: Try[List[Post]] = User.findById(userId).map {
user => Post.findByUser(user)
}
posts match {
case Success(p) => render(p)
case Failure(e) => error(e)
}
Language features - Monad
import Math.abs
type Birds = Int
type Pole = (Birds, Birds)
def landLeft(n: Int, p: Pole):Option[Pole] = p match {
case (left, right) if abs(left + n - right) < 4 => Some(left + n, right)
case _ => None
}
def landRight(n: Int, p: Pole) = p match {
case (left, right) if abs(left - n - right) < 4 => Some(left , right + n)
case _ => None
}
val result = landLeft(1, (0, 0)).
flatMap{ landLeft(2,_:Pole) }.
flatMap{ landRight(5, _:Pole) }
println(result)
9
Language Features - Actor
• a small compute unit, including:
• behaviour
• state
• messaging
Language Features - Actor
• rules of when a actor received a message:
• create a new actor
• send message to a new actor
• define behaviour when next message arrived
• the most important feature
• a actor is always thread safe
• concurrent is multiple actor’s behaviour
Language Features - Actor
class MyActor extends Actor {
def receive = {
case MsgType1 => //do something
case MsgType2 => //do something else
}
}
val actorRef = system.actorOf[Props[MyActor]]
actorRef ! MsgType1
References
• http://twitter.github.io/scala_school/zh_cn/
index.html
• http://twitter.github.io/effectivescala/index-cn.html
• http://typesafe.com/blog/all
• http://www.cakesolutions.net/teamblogs
• http://adit.io/posts/2013-04-17-
functors,_applicatives,_and_monads_in_pictures.html
13

Contenu connexe

Tendances

Post-Free: Life After Free Monads
Post-Free: Life After Free MonadsPost-Free: Life After Free Monads
Post-Free: Life After Free Monads
John De Goes
 
Ozma: Extending Scala with Oz concurrency
Ozma: Extending Scala with Oz concurrencyOzma: Extending Scala with Oz concurrency
Ozma: Extending Scala with Oz concurrency
BeScala
 
Refactoring Functional Type Classes
Refactoring Functional Type ClassesRefactoring Functional Type Classes
Refactoring Functional Type Classes
John De Goes
 

Tendances (11)

Post-Free: Life After Free Monads
Post-Free: Life After Free MonadsPost-Free: Life After Free Monads
Post-Free: Life After Free Monads
 
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
 
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
 
Visualization team presentation
Visualization team presentation Visualization team presentation
Visualization team presentation
 
Scalaz 8: A Whole New Game
Scalaz 8: A Whole New GameScalaz 8: A Whole New Game
Scalaz 8: A Whole New Game
 
Julio Capote, Twitter
Julio Capote, TwitterJulio Capote, Twitter
Julio Capote, Twitter
 
Principled Error Handling with FP
Principled Error Handling with FPPrincipled Error Handling with FP
Principled Error Handling with FP
 
Building a Functional Stream in Scala
Building a Functional Stream in ScalaBuilding a Functional Stream in Scala
Building a Functional Stream in Scala
 
Guava - Elements of Functional Programming
Guava - Elements of Functional Programming Guava - Elements of Functional Programming
Guava - Elements of Functional Programming
 
Ozma: Extending Scala with Oz concurrency
Ozma: Extending Scala with Oz concurrencyOzma: Extending Scala with Oz concurrency
Ozma: Extending Scala with Oz concurrency
 
Refactoring Functional Type Classes
Refactoring Functional Type ClassesRefactoring Functional Type Classes
Refactoring Functional Type Classes
 

En vedette

Monad presentation scala as a category
Monad presentation   scala as a categoryMonad presentation   scala as a category
Monad presentation scala as a category
samthemonad
 
Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)
stasimus
 
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
 
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
 

En vedette (11)

Why functional why scala
Why functional  why scala Why functional  why scala
Why functional why scala
 
Monad presentation scala as a category
Monad presentation   scala as a categoryMonad presentation   scala as a category
Monad presentation scala as a category
 
Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)
 
Introduction to Option monad in Scala
Introduction to Option monad in ScalaIntroduction to Option monad in Scala
Introduction to Option monad in Scala
 
Thinking functional-in-scala
Thinking functional-in-scalaThinking functional-in-scala
Thinking functional-in-scala
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)
 
Developers Summit 2015 - Scala Monad
Developers Summit 2015 - Scala MonadDevelopers Summit 2015 - Scala Monad
Developers Summit 2015 - Scala Monad
 
Advanced Functional Programming in Scala
Advanced Functional Programming in ScalaAdvanced Functional Programming in Scala
Advanced Functional Programming in Scala
 
Scala: functional programming for the imperative mind
Scala: functional programming for the imperative mindScala: functional programming for the imperative mind
Scala: functional programming for the imperative mind
 
Functional Programming Fundamentals
Functional Programming FundamentalsFunctional Programming Fundamentals
Functional Programming Fundamentals
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 

Similaire à Scala the language matters

Five Languages in a Moment
Five Languages in a MomentFive Languages in a Moment
Five Languages in a Moment
Sergio Gil
 
楽々Scalaプログラミング
楽々Scalaプログラミング楽々Scalaプログラミング
楽々Scalaプログラミング
Tomoharu ASAMI
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
Mario Fusco
 
(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
 

Similaire à Scala the language matters (20)

Five Languages in a Moment
Five Languages in a MomentFive Languages in a Moment
Five Languages in a Moment
 
Beginning Scala Svcc 2009
Beginning Scala Svcc 2009Beginning Scala Svcc 2009
Beginning Scala Svcc 2009
 
ITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function ProgrammingITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function Programming
 
Go for Object Oriented Programmers or Object Oriented Programming without Obj...
Go for Object Oriented Programmers or Object Oriented Programming without Obj...Go for Object Oriented Programmers or Object Oriented Programming without Obj...
Go for Object Oriented Programmers or Object Oriented Programming without Obj...
 
Developing High Performance Websites and Modern Apps with JavaScript and HTML5
Developing High Performance Websites and Modern Apps with JavaScript and HTML5Developing High Performance Websites and Modern Apps with JavaScript and HTML5
Developing High Performance Websites and Modern Apps with JavaScript and HTML5
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Scott Anderson [InfluxData] | New & Upcoming Flux Features | InfluxDays 2022
Scott Anderson [InfluxData] | New & Upcoming Flux Features | InfluxDays 2022Scott Anderson [InfluxData] | New & Upcoming Flux Features | InfluxDays 2022
Scott Anderson [InfluxData] | New & Upcoming Flux Features | InfluxDays 2022
 
ProgrammingwithGOLang
ProgrammingwithGOLangProgrammingwithGOLang
ProgrammingwithGOLang
 
楽々Scalaプログラミング
楽々Scalaプログラミング楽々Scalaプログラミング
楽々Scalaプログラミング
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
 
How to make the fastest Router in Python
How to make the fastest Router in PythonHow to make the fastest Router in Python
How to make the fastest Router in Python
 
(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?
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
 
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data EcosystemWprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
 
Learn JavaScript by modeling Rubik Cube
Learn JavaScript by modeling Rubik CubeLearn JavaScript by modeling Rubik Cube
Learn JavaScript by modeling Rubik Cube
 
A bit about Scala
A bit about ScalaA bit about Scala
A bit about Scala
 
Scala
ScalaScala
Scala
 
Project Gålbma – Actors vs Types
Project Gålbma – Actors vs TypesProject Gålbma – Actors vs Types
Project Gålbma – Actors vs Types
 
An Introduction to Scala (2014)
An Introduction to Scala (2014)An Introduction to Scala (2014)
An Introduction to Scala (2014)
 
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
 

Dernier

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Dernier (20)

Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 

Scala the language matters

  • 3. Language features - functions • high order function 3
  • 4. Language - Implicit • implicit convention
  • 5. Language - Implicit val personJson = """{ "name": "Jason" }”"" val r1 = httpClient(Request( GET, new URI("http://api.rest.org/person/"), Map(), None)) val r2 = httpClient(Request( POST, new URI("http://api.rest.org/person/"), Map(), Some(personJson))) val id = r2.headers(“X-Person-Id").head val r3 = httpClient(Request( GET, new URI("http://api.rest.org/person/" + id), Map(), None)) val r4 = httpClient(Request( GET, new URI("http://api.rest.org/person/"), Map(), None)) val r5 = httpClient(Request( DELETE, new URI("http://api.rest.org/person/" + id), Map(), None))
  • 6. Language - Implicit using(_ url "http://api.rest.org") { implicit rb => GET / "person" asserting (StatusCode === Status.OK, BodyAsPersonList === EmptyList) val id = POST / "person" body personJson asserting (StatusCode === Status.Created) returning (header(“X-Person-Id")) GET / "person" / id asserting (StatusCode === Status.OK, BodyAsPerson === Jason) GET / "person" asserting (StatusCode === Status.OK, BodyAsPersonList === Seq(Jason)) DELETE / "person" / id asserting (StatusCode === Status.OK) GET / "person" asserting (StatusCode === Status.OK, BodyAsPersonList === EmptyList) }
  • 7. Language Feature - Monad sealed abstract class Try[+T] case class Success[+T](value: T) case class Failure[+T](exception: Throwable) case abstract class Option[T] case class Some[T] case object None extends Option[Nothing] {//…}
  • 8. Language Feature - Monad //in User def findById(id: Long):Try[User] = { //Success(user) or Failure(e) } //in Post def findByUser(user: User):Try[List[Post]] = { //Success(posts)or Failure(e) } val posts: Try[List[Post]] = User.findById(userId).map { user => Post.findByUser(user) } posts match { case Success(p) => render(p) case Failure(e) => error(e) }
  • 9. Language features - Monad import Math.abs type Birds = Int type Pole = (Birds, Birds) def landLeft(n: Int, p: Pole):Option[Pole] = p match { case (left, right) if abs(left + n - right) < 4 => Some(left + n, right) case _ => None } def landRight(n: Int, p: Pole) = p match { case (left, right) if abs(left - n - right) < 4 => Some(left , right + n) case _ => None } val result = landLeft(1, (0, 0)). flatMap{ landLeft(2,_:Pole) }. flatMap{ landRight(5, _:Pole) } println(result) 9
  • 10. Language Features - Actor • a small compute unit, including: • behaviour • state • messaging
  • 11. Language Features - Actor • rules of when a actor received a message: • create a new actor • send message to a new actor • define behaviour when next message arrived • the most important feature • a actor is always thread safe • concurrent is multiple actor’s behaviour
  • 12. Language Features - Actor class MyActor extends Actor { def receive = { case MsgType1 => //do something case MsgType2 => //do something else } } val actorRef = system.actorOf[Props[MyActor]] actorRef ! MsgType1
  • 13. References • http://twitter.github.io/scala_school/zh_cn/ index.html • http://twitter.github.io/effectivescala/index-cn.html • http://typesafe.com/blog/all • http://www.cakesolutions.net/teamblogs • http://adit.io/posts/2013-04-17- functors,_applicatives,_and_monads_in_pictures.html 13