- Typeclasses in Scala allow defining common behavior (like printing) for unrelated types through implicit parameters and resolution. This avoids needing to modify types to add functionality.
- They work by defining typeclass traits that take a type parameter (like Show[T]), providing implicit values that implement traits for specific types, and having methods use implicit parameters of the typeclass.
- While powerful, typeclasses can cause issues like ambiguous implicits and lack consistency when multiple instances are defined. The Shapeless library addresses some limitations by allowing automatic typeclass instance derivation based on a type's structure.
12. ● Doit être implémenté à la déclaration du type
● Compliqué à implémenter pour les types existants
● Complexifie la hiérarchie de types
● Mélange technique et métier
● Impossible d’implémenter un autre comportement
12
38. implicit def genericShow[A, R](implicit gen: Generic[A] {type Repr = R},
s: Show[R]): Show[A] =
new Show[A] {
override def show(a: A) = s.encode(gen.to(a))
}
Si l’on sait transformer une classe A en HList R, et que l’on sait sérialiser une HList R, alors
on sait sérialiser une classe A
38