Skip to content

A typeclass primer for OO people

Photo of Yann Simon
Hosted By
Yann S. and 2 others
A typeclass primer for OO people

Details

Hi Scalaties,
after Hermanns introduction to type classes, Simon Hafner will give us a more in depth explanation about this power full concept.

This talk will explain how to connect functions to types, using typeclasses. It will mention common use cases, problems, and the implementations of typeclasses in both Scala and Haskell. No prior knowledge of Scala or Haskell is required.

In Object Oriented programming, objects consist of three components: data, methods, and state. When written in an FP style, these objects will only consist of data and pure methods. However, there is no requirement for data and methods/functions to stay together, because there's no associated state.

Because a method/function doesn't need an attached object anymore, it's also possible to attach it to the type instead. The concept of attaching different functions to different types, with all the functions of the same signature, is called a typeclass.

A typeclass is a way to declare an API, similar to an interface in Java. It is then implemented for different types, similar to an interface. Each implementation is then associated with the corresponding type. This idea will be demonstrated with the Functor typeclass.

Typeclasses are a strict superset of interfaces in terms of implementation power. This will be demonstrated with the Monoid typeclass.

The concept of typeclasses will be applied on two separate use cases: counting words in documents, and JSON codecs. Counting words will be based on Monoids, the JSON codecs will demonstrate the association between types and functions. Each of the examples will also showcase some of the problems with typeclasses.

Each of the use cases will be demonstrated in Scala and Haskell, to highlight the different implementation of typeclasses. The differences are mostly in the resolution on which function to pick, and the so-called typeclass coherence.

Photo of Scala User Group - Berlin Brandenburg group
Scala User Group - Berlin Brandenburg
See more events
leanovate GmbH
Blücherstr. 22 · 10961 Berlin