Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type class pattern vs implicit class

Tags:

scala

I have a hard time understanding the difference in use cases between teh type class pattern and the implicit class in Scala. What makes it confusing for me is that they both provide ad hoc polimorphism in Scala.

My question is. Are they solving the same problem or is there a clear difference in use cases?

like image 598
user3139545 Avatar asked Dec 06 '25 08:12

user3139545


1 Answers

There is a difference.

Implicit classes are usually used to provide extension methods to existing types:

implicit class IntExt(val x: Int) extends AnyVal {
  def squared: Int = x * x
}

10.squared shouldEqual 1000

They do not actually provide an ad-hoc polymorphism; it's just an ability to define new methods on existing types.

Type classes, on the other hand, depend on another implicit mechanism (implicit parameters vs implicit conversions in case of implicit classes), and they are a mechanism of ad-hoc polymorphism:

trait Show[T] {
  def show(x: T): String
}

implicit val intHexShow: Show[Int] = new Show[Int] {
  override def show(x: Int): String = Integer.toHexString(x)
}

implicit val stringReverseShow: Show[String] = new Show[String] {
  override def show(x: String): String = x.reverse
}

def showPrint[T](value: T)(implicit s: Show[T]): Unit = {
  println(s.show(value))
}

showPrint(12)  // prints "c"
showPrint("hello")  // prints "olleh"

Since the function with the respective implicit parameter accepts the "behavior" defined in a type class implementation for a particular type as a parameter, it is indeed a case of ad-hoc polymorphism. Type classes are used for lots of things in Scala: JSON encoding/decoding, functional structures like monads and applicatives, type-polymorphic functions, to name a few. Almost everywhere when you need to add new behavior to existing types in a generic way, you will encounter a type class.

like image 76
Vladimir Matveev Avatar answered Dec 08 '25 22:12

Vladimir Matveev