September 2018
Intermediate to advanced
398 pages
9h 43m
English
Now, we would like to model the opposite of decoding a string to an object—encoding an object to a string! We make our Encoder contravariant by adding a - sign in front of the A type parameter, as shown in the following code:
trait Encoder[-A] { def encode(a: A): String}
The following code is an instance of this Encoder:
object AnimalEncoder extends Encoder[Animal] { def encode(a: Animal): String = a.toString}
We have the Cat <:< Animal relationship, and Encoder is contravariant on its argument. This implies that Encoder[Animal] <:< Encoder[Cat], and I can, therefore, assign Encoder[Animal] to a variable of type Encoder[Cat], as shown in the following code:
val catEncoder: Encoder[Cat] = AnimalEncodercatEncoder.encode( ...Read now
Unlock full access