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
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
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