scala with cats Flashcards
A Type Class is…
Interface or API that represents some functionality we want to implement. Represented by a Trait with at least One Type Parameter.
Type Class Instances
Provide implementations for the Types
Type Class Interface
Functionality exposed to usersGeneric methods that accept instances of the Type Class as implicit parameters- Interface Objects: place methods in a singleton object- Interface Syntax: use extension methods to extendexiting Types with interface methods
The ‘implicitly’ Method
Scala generic Type Class InterfaceSummon any value from Implicit ScopeNote: - Good fallback for debugging purposes, the compiler will ensure it can find an instance of the type and that there are not ambiguous- Type Classes in Scala means working with Implicit Values and Implicit Parameters- Implicit
in Scala must be placed inside an Object or Trait
Type Class Definitions are only included in Implicit Scope if …
They are tagged with the ‘implicit’ keywordNote:- the compiler searches for candidate Type Class Instances by Type in the Implicit Scope at the call site - in local or inherited Definitions - in imported Definitions - in the Companion Object of the Type Class or the Parameter Type - if the compiler sees multiple candidate Definitions, it fails with an ambiguous implicit values error- The power of Type Classes and Implicit lies in the compiler’s ability to Combine Implicit Definitions when searching for candidate Instances- We can define Instances in two ways - By defining concrete Instances as Implicit Vals
of the required Type - By defining Implicit Methods
to construct Instances from other Type Class instances example: JsonWriter[A] and JsonWriter[Option[A]] - Be sure to mark the parameters to the method as implicit parameters.
Implicit methods with non-implicit parameters form a different Scala pattern called an …
Implicit Conversion (frowned upon)
Cats is written using a …
Modular Structure that allows us to choose which Type Classes, Instances, and Interface Methods we want to use.Note: - import cats._ imports all of Cats’ Type Classes- import cats.instances.all._ imports all of the Type Class Instances for the Standard Pibrary- import cats.syntax.all._ imports all of the Syntax- import cats.implicits._ imports all of the Standard Type Class Instances and all of the Syntax
When working with Type Classes we must consider two issues that control instance selection
The relationship between an Instance defined on a Type and its SubtypesHow do we choose between Type Class Instances when there are many available