Jakub Arnold
Jakub Arnold

Reputation: 87210

How can I emulate Haskell's typeclasses in Scala?

Is there a way to define something like a typeclass (probably a trait?), and then later define an instance of that typeclass for a specific type, without modifying the original type definition?

For example, having the following code

class User {
}

trait Printable {
  def print(): String
}

Can I somehow make the User class Printable separately from the class definition, without having to say class User extends Printable?

Upvotes: 1

Views: 151

Answers (1)

Lee
Lee

Reputation: 144136

You create a trait for the typeclass you want to define e.g.

trait Printable[T] {
   def print(p: T): String
}

then you can define implicit instances of this trait for the types you want:

object Instances {
    implicit val UserPrintable = new Printable[User] {
        def print(u: User) = u.name
    }
}

in any functions that require the typeclass you can add an implicit parameter for the instance:

def writePrintable[T](p: T)(implicit pclass: Printable[T]) {
    println(pclass.print(p))
}

then you can call writePrintable by importing the instance implementation e.g.

import Instances._
writePrintable(new User("user name"))

Upvotes: 3

Related Questions