SlideShare une entreprise Scribd logo
1  sur  18
Télécharger pour lire hors ligne
type classes in Scala
And how Json Reads/Writes/Formats
work in play framework?
Yann Simon - @simon_yann
toString, hashCode on model
case class Person(name: String, age: Int)



val persons =

List(

Person("bob", 34),

Person("alice", 34))

persons.toString()

res0: String = List(Person(bob,34), Person(alice,34))
persons.hashCode()
res1: Int = -408691241
persons.toString
toString()List
Person
String Int
toString()
toString() toString()
persons.hashCode
hashCodeList
Person
String Int
hashCode
hashCode hashCode
What about persons.toJson?
persons.toXML? .toCSV?
persons.otherHashCode?
persons.otherToString?
Why persons.toString?
persons.hashCode?
• part of the standard JVM library
package java.lang;



public class Object {

public native int hashCode();

public boolean equals(Object obj) { … }

public String toString() { … }
public final native void notify();

public final native void notifyAll();

public final native void wait(long timeout) throws InterruptedException;

public final void wait(long timeout, int nanos) throws InterruptedException { … }

public final void wait() throws InterruptedException { … }
}
Why persons.toString?
persons.hashCode?
• needed by Map, Set, serialization…
• mix technical concerns with domain model
• no liberty for further improvement
• ex: #2011-003 multiple implementations denial-of-
service via hash algorithm collision

A variety of programming languages suffer from a denial-of-service
(DoS) condition against storage functions of key/value pairs in hash
data structures, the condition can be leveraged by exploiting
predictable collisions in the underlying hashing algorithms.
a good toJson?
• Separated from domain model
• Flexible
• User can override library choices
persons to json
List
Person
String Int
listToJson
personToJson
stringToJson intToJson
trait toJson[A]
ToJson[A] strategy is a
parameter of toJson[A]
def toJson[A](a: A)(serializer: ToJson[A]): String =

serializer.serialize(a)



toJson("hello")(stringToJson)

toJson(3)(intToJson)

toJson(Person("bob", 34))(personToJson)

toJson(persons)(listToJson(personToJson))
find the right ToJson[A]
based on type
def toJson[A](a: A)(implicit serializer: ToJson[A]): String =

serializer.serialize(a)



toJson("hello")

toJson(3)

toJson(Person("bob", 34))

toJson(persons)
find the right ToJson[A]
based on type
toJson("hello")
// is different from
toJson(3)

$ scalac -Xprint:4 Test.scala
[…]
Test.this.toJson[String]("hello")(Test.this.stringToJson);
Test.this.toJson[Int](3)(Test.this.intToJson);
Type classes
• Define a contract (ex in ToJson[A]: (a: A) -> String)
• Define strategy for a tree of classes (like the domain model)
• Use type for find the suitable implementation
• Each implicit can be overridden / set explicitly => the user has the
power to override defaults
• Type classes resolved at compilation time
• Be sure that the strategy is defined for each class
• No runtime introspection necessary
In Play! framework
package play.api.libs.json

object Json {

def toJson[T](o: T)(implicit tjs: Writes[T]): JsValue = tjs.writes(o)

def fromJson[T](json: JsValue)(implicit fjs: Reads[T]): JsResult[T] =
fjs.reads(json)
}
/**

* Default Serializers.

*/

trait DefaultWrites {

implicit object IntWrites extends Writes[Int] {

def writes(o: Int) = JsNumber(o)

}

implicit object StringWrites extends Writes[String] {

def writes(o: String) = JsString(o)

}

implicit def traversableWrites[A: Writes] = new Writes[Traversable[A]] {

def writes(as: Traversable[A]) = JsArray(as.map(toJson(_)).toSeq)

}

}
In Play! framework
package play.api.libs.json

trait Format[A] extends Writes[A] with Reads[A]

/**

* Default Json formatters.

*/

trait DefaultFormat {



implicit def GenericFormat[T](implicit fjs: Reads[T], tjs: Writes[T]):
Format[T] = {

new Format[T] {

def reads(json: JsValue) = fjs.reads(json)

def writes(o: T) = tjs.writes(o)

}

}



}
implicitly syntax
def toJson[A](a: A)(implicit toJson: ToJson[A]): String =

toJson.serialize(a)
// can be written as:

def toJson[A : ToJson](a: A): String =

implicitly[ToJson[A]].serialize(a)


toJson("hello")

toJson(3)

toJson(Person("bob", 34))

toJson(persons)
persons.toJson
implicit class JsonOps[A](a: A)(implicit ser: ToJson[A]) {

def toJson: String = ser.serialize(a)

}



"hello".toJson

3.toJson

Person("bob", 34).toJson

persons.toJson
Questions?
• code on https://github.com/yanns/scala-type-classes-
demo
• more info:
• https://non.github.io/cats/typeclasses.html
• http://danielwestheide.com/blog/2013/02/06/the-
neophytes-guide-to-scala-part-12-type-classes.html

Contenu connexe

Tendances

The Ring programming language version 1.7 book - Part 78 of 196
The Ring programming language version 1.7 book - Part 78 of 196The Ring programming language version 1.7 book - Part 78 of 196
The Ring programming language version 1.7 book - Part 78 of 196Mahmoud Samir Fayed
 
The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84Mahmoud Samir Fayed
 
The Ring programming language version 1.4 book - Part 20 of 30
The Ring programming language version 1.4 book - Part 20 of 30The Ring programming language version 1.4 book - Part 20 of 30
The Ring programming language version 1.4 book - Part 20 of 30Mahmoud Samir Fayed
 
The Ring programming language version 1.6 book - Part 182 of 189
The Ring programming language version 1.6 book - Part 182 of 189The Ring programming language version 1.6 book - Part 182 of 189
The Ring programming language version 1.6 book - Part 182 of 189Mahmoud Samir Fayed
 
20170113 julia’s type system and multiple dispatch
20170113 julia’s type system and multiple dispatch20170113 julia’s type system and multiple dispatch
20170113 julia’s type system and multiple dispatch岳華 杜
 
Demystifying Shapeless
Demystifying Shapeless Demystifying Shapeless
Demystifying Shapeless Jared Roesch
 
Strings In OOP(Object oriented programming)
Strings In OOP(Object oriented programming)Strings In OOP(Object oriented programming)
Strings In OOP(Object oriented programming)Danial Virk
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20myrajendra
 
‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3Mahmoud Alfarra
 
البرمجة الهدفية بلغة جافا - مفاهيم أساسية
البرمجة الهدفية بلغة جافا - مفاهيم أساسية البرمجة الهدفية بلغة جافا - مفاهيم أساسية
البرمجة الهدفية بلغة جافا - مفاهيم أساسية Mahmoud Alfarra
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanKavita Ganesan
 
Super keyword.23
Super keyword.23Super keyword.23
Super keyword.23myrajendra
 
String java
String javaString java
String java774474
 
C h 04 oop_inheritance
C h 04 oop_inheritanceC h 04 oop_inheritance
C h 04 oop_inheritanceshatha00
 
Java string handling
Java string handlingJava string handling
Java string handlingSalman Khan
 

Tendances (19)

The Ring programming language version 1.7 book - Part 78 of 196
The Ring programming language version 1.7 book - Part 78 of 196The Ring programming language version 1.7 book - Part 78 of 196
The Ring programming language version 1.7 book - Part 78 of 196
 
The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84
 
The Ring programming language version 1.4 book - Part 20 of 30
The Ring programming language version 1.4 book - Part 20 of 30The Ring programming language version 1.4 book - Part 20 of 30
The Ring programming language version 1.4 book - Part 20 of 30
 
The Ring programming language version 1.6 book - Part 182 of 189
The Ring programming language version 1.6 book - Part 182 of 189The Ring programming language version 1.6 book - Part 182 of 189
The Ring programming language version 1.6 book - Part 182 of 189
 
20170113 julia’s type system and multiple dispatch
20170113 julia’s type system and multiple dispatch20170113 julia’s type system and multiple dispatch
20170113 julia’s type system and multiple dispatch
 
Demystifying Shapeless
Demystifying Shapeless Demystifying Shapeless
Demystifying Shapeless
 
scala-101
scala-101scala-101
scala-101
 
Strings In OOP(Object oriented programming)
Strings In OOP(Object oriented programming)Strings In OOP(Object oriented programming)
Strings In OOP(Object oriented programming)
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVA
 
06. haskell type builder
06. haskell type builder06. haskell type builder
06. haskell type builder
 
Java session4
Java session4Java session4
Java session4
 
‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3
 
البرمجة الهدفية بلغة جافا - مفاهيم أساسية
البرمجة الهدفية بلغة جافا - مفاهيم أساسية البرمجة الهدفية بلغة جافا - مفاهيم أساسية
البرمجة الهدفية بلغة جافا - مفاهيم أساسية
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
 
Super keyword.23
Super keyword.23Super keyword.23
Super keyword.23
 
String java
String javaString java
String java
 
C h 04 oop_inheritance
C h 04 oop_inheritanceC h 04 oop_inheritance
C h 04 oop_inheritance
 
Java string handling
Java string handlingJava string handling
Java string handling
 

En vedette

Scala Type Classes: Basics and More
Scala Type Classes:  Basics and MoreScala Type Classes:  Basics and More
Scala Type Classes: Basics and Moresukanthajra
 
Type class polymorphism
Type class polymorphismType class polymorphism
Type class polymorphismMayank Bairagi
 
Why scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with thisWhy scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with thisRuslan Shevchenko
 
42.type: Literal-based Singleton types
42.type: Literal-based Singleton types42.type: Literal-based Singleton types
42.type: Literal-based Singleton typesGeorge Leontiev
 
Few simple-type-tricks in scala
Few simple-type-tricks in scalaFew simple-type-tricks in scala
Few simple-type-tricks in scalaRuslan Shevchenko
 
Generics Past, Present and Future (Latest)
Generics Past, Present and Future (Latest)Generics Past, Present and Future (Latest)
Generics Past, Present and Future (Latest)RichardWarburton
 
Practical type mining in Scala
Practical type mining in ScalaPractical type mining in Scala
Practical type mining in ScalaRose Toomey
 
Introducing Monads and State Monad at PSUG
Introducing Monads and State Monad at PSUGIntroducing Monads and State Monad at PSUG
Introducing Monads and State Monad at PSUGDavid Galichet
 
Writing DSL with Applicative Functors
Writing DSL with Applicative FunctorsWriting DSL with Applicative Functors
Writing DSL with Applicative FunctorsDavid Galichet
 
Playing with State Monad
Playing with State MonadPlaying with State Monad
Playing with State MonadDavid Galichet
 
Demystifying Scala Type System
Demystifying Scala Type SystemDemystifying Scala Type System
Demystifying Scala Type SystemDavid Galichet
 

En vedette (11)

Scala Type Classes: Basics and More
Scala Type Classes:  Basics and MoreScala Type Classes:  Basics and More
Scala Type Classes: Basics and More
 
Type class polymorphism
Type class polymorphismType class polymorphism
Type class polymorphism
 
Why scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with thisWhy scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with this
 
42.type: Literal-based Singleton types
42.type: Literal-based Singleton types42.type: Literal-based Singleton types
42.type: Literal-based Singleton types
 
Few simple-type-tricks in scala
Few simple-type-tricks in scalaFew simple-type-tricks in scala
Few simple-type-tricks in scala
 
Generics Past, Present and Future (Latest)
Generics Past, Present and Future (Latest)Generics Past, Present and Future (Latest)
Generics Past, Present and Future (Latest)
 
Practical type mining in Scala
Practical type mining in ScalaPractical type mining in Scala
Practical type mining in Scala
 
Introducing Monads and State Monad at PSUG
Introducing Monads and State Monad at PSUGIntroducing Monads and State Monad at PSUG
Introducing Monads and State Monad at PSUG
 
Writing DSL with Applicative Functors
Writing DSL with Applicative FunctorsWriting DSL with Applicative Functors
Writing DSL with Applicative Functors
 
Playing with State Monad
Playing with State MonadPlaying with State Monad
Playing with State Monad
 
Demystifying Scala Type System
Demystifying Scala Type SystemDemystifying Scala Type System
Demystifying Scala Type System
 

Similaire à Introduction to type classes in Scala

String and string manipulation
String and string manipulationString and string manipulation
String and string manipulationShahjahan Samoon
 
Basics of Python programming (part 2)
Basics of Python programming (part 2)Basics of Python programming (part 2)
Basics of Python programming (part 2)Pedro Rodrigues
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation xShahjahan Samoon
 
L13 string handling(string class)
L13 string handling(string class)L13 string handling(string class)
L13 string handling(string class)teach4uin
 
Arrays string handling java packages
Arrays string handling java packagesArrays string handling java packages
Arrays string handling java packagesSardar Alam
 
The Ring programming language version 1.7 book - Part 39 of 196
The Ring programming language version 1.7 book - Part 39 of 196The Ring programming language version 1.7 book - Part 39 of 196
The Ring programming language version 1.7 book - Part 39 of 196Mahmoud Samir Fayed
 
Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - StockholmJan Kronquist
 
Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and HaskellHermann Hueck
 
Java 5 New Feature
Java 5 New FeatureJava 5 New Feature
Java 5 New Featurexcoda
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumarSujith Kumar
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecLoïc Descotte
 
The Ring programming language version 1.5.1 book - Part 34 of 180
The Ring programming language version 1.5.1 book - Part 34 of 180The Ring programming language version 1.5.1 book - Part 34 of 180
The Ring programming language version 1.5.1 book - Part 34 of 180Mahmoud Samir Fayed
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#Doncho Minkov
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingGarth Gilmour
 

Similaire à Introduction to type classes in Scala (20)

String and string manipulation
String and string manipulationString and string manipulation
String and string manipulation
 
Basics of Python programming (part 2)
Basics of Python programming (part 2)Basics of Python programming (part 2)
Basics of Python programming (part 2)
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation x
 
L13 string handling(string class)
L13 string handling(string class)L13 string handling(string class)
L13 string handling(string class)
 
Arrays string handling java packages
Arrays string handling java packagesArrays string handling java packages
Arrays string handling java packages
 
The Ring programming language version 1.7 book - Part 39 of 196
The Ring programming language version 1.7 book - Part 39 of 196The Ring programming language version 1.7 book - Part 39 of 196
The Ring programming language version 1.7 book - Part 39 of 196
 
Struktur data 1
Struktur data 1Struktur data 1
Struktur data 1
 
CAP615-Unit1.pptx
CAP615-Unit1.pptxCAP615-Unit1.pptx
CAP615-Unit1.pptx
 
Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - Stockholm
 
core java
 core java core java
core java
 
Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and Haskell
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Java 5 New Feature
Java 5 New FeatureJava 5 New Feature
Java 5 New Feature
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
Meet scala
Meet scalaMeet scala
Meet scala
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
The Ring programming language version 1.5.1 book - Part 34 of 180
The Ring programming language version 1.5.1 book - Part 34 of 180The Ring programming language version 1.5.1 book - Part 34 of 180
The Ring programming language version 1.5.1 book - Part 34 of 180
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
 

Plus de yann_s

FS2 mongo reactivestreams
FS2 mongo reactivestreamsFS2 mongo reactivestreams
FS2 mongo reactivestreamsyann_s
 
Bringing a public GraphQL API from the whiteboard to production
Bringing a public GraphQL API from the whiteboard to productionBringing a public GraphQL API from the whiteboard to production
Bringing a public GraphQL API from the whiteboard to productionyann_s
 
Bringing a public GraphQL API from beta to production ready
Bringing a public GraphQL API from beta to production readyBringing a public GraphQL API from beta to production ready
Bringing a public GraphQL API from beta to production readyyann_s
 
Introduction to rust: a low-level language with high-level abstractions
Introduction to rust: a low-level language with high-level abstractionsIntroduction to rust: a low-level language with high-level abstractions
Introduction to rust: a low-level language with high-level abstractionsyann_s
 
Performance optimisation with GraphQL
Performance optimisation with GraphQLPerformance optimisation with GraphQL
Performance optimisation with GraphQLyann_s
 
Introduction to GraphQL at API days
Introduction to GraphQL at API daysIntroduction to GraphQL at API days
Introduction to GraphQL at API daysyann_s
 
Compile time dependency injection in Play 2.4 with macwire
Compile time dependency injection in Play 2.4 with macwireCompile time dependency injection in Play 2.4 with macwire
Compile time dependency injection in Play 2.4 with macwireyann_s
 
Structure your Play application with the cake pattern (and test it)
Structure your Play application with the cake pattern (and test it)Structure your Play application with the cake pattern (and test it)
Structure your Play application with the cake pattern (and test it)yann_s
 

Plus de yann_s (8)

FS2 mongo reactivestreams
FS2 mongo reactivestreamsFS2 mongo reactivestreams
FS2 mongo reactivestreams
 
Bringing a public GraphQL API from the whiteboard to production
Bringing a public GraphQL API from the whiteboard to productionBringing a public GraphQL API from the whiteboard to production
Bringing a public GraphQL API from the whiteboard to production
 
Bringing a public GraphQL API from beta to production ready
Bringing a public GraphQL API from beta to production readyBringing a public GraphQL API from beta to production ready
Bringing a public GraphQL API from beta to production ready
 
Introduction to rust: a low-level language with high-level abstractions
Introduction to rust: a low-level language with high-level abstractionsIntroduction to rust: a low-level language with high-level abstractions
Introduction to rust: a low-level language with high-level abstractions
 
Performance optimisation with GraphQL
Performance optimisation with GraphQLPerformance optimisation with GraphQL
Performance optimisation with GraphQL
 
Introduction to GraphQL at API days
Introduction to GraphQL at API daysIntroduction to GraphQL at API days
Introduction to GraphQL at API days
 
Compile time dependency injection in Play 2.4 with macwire
Compile time dependency injection in Play 2.4 with macwireCompile time dependency injection in Play 2.4 with macwire
Compile time dependency injection in Play 2.4 with macwire
 
Structure your Play application with the cake pattern (and test it)
Structure your Play application with the cake pattern (and test it)Structure your Play application with the cake pattern (and test it)
Structure your Play application with the cake pattern (and test it)
 

Dernier

"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
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 CVKhem
 
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 RobisonAnna Loughnan Colquhoun
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
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 Scriptwesley chun
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
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 DevelopmentsTrustArc
 

Dernier (20)

"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
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
 
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
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
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
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
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
 

Introduction to type classes in Scala

  • 1. type classes in Scala And how Json Reads/Writes/Formats work in play framework? Yann Simon - @simon_yann
  • 2. toString, hashCode on model case class Person(name: String, age: Int)
 
 val persons =
 List(
 Person("bob", 34),
 Person("alice", 34))
 persons.toString()
 res0: String = List(Person(bob,34), Person(alice,34)) persons.hashCode() res1: Int = -408691241
  • 5. What about persons.toJson? persons.toXML? .toCSV? persons.otherHashCode? persons.otherToString?
  • 6. Why persons.toString? persons.hashCode? • part of the standard JVM library package java.lang;
 
 public class Object {
 public native int hashCode();
 public boolean equals(Object obj) { … }
 public String toString() { … } public final native void notify();
 public final native void notifyAll();
 public final native void wait(long timeout) throws InterruptedException;
 public final void wait(long timeout, int nanos) throws InterruptedException { … }
 public final void wait() throws InterruptedException { … } }
  • 7. Why persons.toString? persons.hashCode? • needed by Map, Set, serialization… • mix technical concerns with domain model • no liberty for further improvement • ex: #2011-003 multiple implementations denial-of- service via hash algorithm collision
 A variety of programming languages suffer from a denial-of-service (DoS) condition against storage functions of key/value pairs in hash data structures, the condition can be leveraged by exploiting predictable collisions in the underlying hashing algorithms.
  • 8. a good toJson? • Separated from domain model • Flexible • User can override library choices
  • 9. persons to json List Person String Int listToJson personToJson stringToJson intToJson trait toJson[A]
  • 10. ToJson[A] strategy is a parameter of toJson[A] def toJson[A](a: A)(serializer: ToJson[A]): String =
 serializer.serialize(a)
 
 toJson("hello")(stringToJson)
 toJson(3)(intToJson)
 toJson(Person("bob", 34))(personToJson)
 toJson(persons)(listToJson(personToJson))
  • 11. find the right ToJson[A] based on type def toJson[A](a: A)(implicit serializer: ToJson[A]): String =
 serializer.serialize(a)
 
 toJson("hello")
 toJson(3)
 toJson(Person("bob", 34))
 toJson(persons)
  • 12. find the right ToJson[A] based on type toJson("hello") // is different from toJson(3)
 $ scalac -Xprint:4 Test.scala […] Test.this.toJson[String]("hello")(Test.this.stringToJson); Test.this.toJson[Int](3)(Test.this.intToJson);
  • 13. Type classes • Define a contract (ex in ToJson[A]: (a: A) -> String) • Define strategy for a tree of classes (like the domain model) • Use type for find the suitable implementation • Each implicit can be overridden / set explicitly => the user has the power to override defaults • Type classes resolved at compilation time • Be sure that the strategy is defined for each class • No runtime introspection necessary
  • 14. In Play! framework package play.api.libs.json
 object Json {
 def toJson[T](o: T)(implicit tjs: Writes[T]): JsValue = tjs.writes(o)
 def fromJson[T](json: JsValue)(implicit fjs: Reads[T]): JsResult[T] = fjs.reads(json) } /**
 * Default Serializers.
 */
 trait DefaultWrites {
 implicit object IntWrites extends Writes[Int] {
 def writes(o: Int) = JsNumber(o)
 }
 implicit object StringWrites extends Writes[String] {
 def writes(o: String) = JsString(o)
 }
 implicit def traversableWrites[A: Writes] = new Writes[Traversable[A]] {
 def writes(as: Traversable[A]) = JsArray(as.map(toJson(_)).toSeq)
 }
 }
  • 15. In Play! framework package play.api.libs.json
 trait Format[A] extends Writes[A] with Reads[A]
 /**
 * Default Json formatters.
 */
 trait DefaultFormat {
 
 implicit def GenericFormat[T](implicit fjs: Reads[T], tjs: Writes[T]): Format[T] = {
 new Format[T] {
 def reads(json: JsValue) = fjs.reads(json)
 def writes(o: T) = tjs.writes(o)
 }
 }
 
 }
  • 16. implicitly syntax def toJson[A](a: A)(implicit toJson: ToJson[A]): String =
 toJson.serialize(a) // can be written as:
 def toJson[A : ToJson](a: A): String =
 implicitly[ToJson[A]].serialize(a) 
 toJson("hello")
 toJson(3)
 toJson(Person("bob", 34))
 toJson(persons)
  • 17. persons.toJson implicit class JsonOps[A](a: A)(implicit ser: ToJson[A]) {
 def toJson: String = ser.serialize(a)
 }
 
 "hello".toJson
 3.toJson
 Person("bob", 34).toJson
 persons.toJson
  • 18. Questions? • code on https://github.com/yanns/scala-type-classes- demo • more info: • https://non.github.io/cats/typeclasses.html • http://danielwestheide.com/blog/2013/02/06/the- neophytes-guide-to-scala-part-12-type-classes.html