1 of 13

Typeclass in Scala

Walter Chang 張瑋修

weihsiu@gmail.com

+weihsiu

@weihsiu

2 of 13

What we will cover today

  • A little history
  • Why typeclass
  • Relevant features
  • Alternatives
  • A little terminology
  • Our first typeclass
  • First use case
  • Second use case
  • The M word
  • Higher-kinded type
  • Questions.map(Answer(_))

3 of 13

A little history

  • Invented by Philip Wadler for Haskell
  • A language feature in Haskell
  • A design pattern for Scala
    • A little like the strategy pattern
    • Separation between data and behavior
  • Type class vs. Typeclass

4 of 13

Why typeclass

  • Polymorphism (allows values of different data types to be handled using a uniform interface)
    • Types of polymorphism
      • Subtype
      • Parametric
        • Allows a function or data type to be written generically, so that it can handle values identically without depending on their types.
      • Ad-hoc (overloading)
        • Functions which can be applied to arguments of different types, but which behave differently depending on the type of the argument to which they are applied.
  • Decoupling
  • Retroactive extension
  • Binary Resilience

5 of 13

Relevant features

  • Traits trait Logger[A] { def info(msg: String) }
  • Companion objects object Logger { ... }
  • Implicits definitions implicit val defaultLogger = ...
  • Curry functions def add(x: Int)(y: Int) = x + y // Int => Int => Int
  • Implicit parameter def info[A](msg: String)(implicit logger: Logger[A])
  • Generic types type IntList = List[Int]
  • Type constructors A[_]

6 of 13

Alternatives

  • Method overloading
  • Pattern matching
  • Inheritance (subtyping)
  • Example: Serializable.scala

serialize(123)

serialize("hello world")

serialize(List(1, 2, 3))

serialize(Map('a -> 1, 'b -> 2, 'c -> 3))

7 of 13

A little terminology

  • Typeclasses

trait Serializable[A] {

def serialize(x: A): String

}

  • Typeclass instances

object Serializable {

implicit val itemSerializable = new Serializable[Item] {

def serialize(x: Item) = ???

}

}

  • Functions/methods that use typeclasses

def serialize[A](x: A)(implicit s: Serializable[A]): String = s.serialize(x)

8 of 13

Our first typeclass

Ords.scala

9 of 13

First use case

Coerces.scala

10 of 13

Second use case

ShowReads.scala

11 of 13

The M word

Monoids.scala

12 of 13

Higher-kinded type

Foldables.scala

13 of 13

Questions.map(Answer(_))