Scala — Beau[T]y of Type classes

Kumar Nellipudi
1 min readDec 17, 2021

What is typesafety?

Enforcing type of a value to be confirmed over compilation rather than being hit by a bump in run-time.

It will lets you add new behavior to closed data types without using inheritance

Is that a good idea to make models bounded to a region? definitely it works, it will never gives you runtime surprises.

Draft Key: I have to cover implicits & it’s working mechanism before completing this article

Find out an example given by daniel here. (I will explain who is daniel later)

trait Summable[T] {
def sumElements(list: List[T]): T
}

This is a trait that defines the capability of aggregating a list into a single element. We can of course add some implementations for Int and String, the way we like it:

implicit object IntSummable extends Summable[Int] {
def sumElements(list: List[Int]): Int = list.sum
}
implicit object StringSummable extends Summable[String] {
def sumElements(list: List[String]): String = list.mkString("")
}

As you can see, two very different implementations of the “sum” we can perform. We can then enhance the original method like this:

def processMyList[T](list: List[T])(implicit summable: Summable[T]): T =
summable.sumElements(list)

If you try this, you will notice that it works for Strings and Ints, and it doesn’t even compile for anything else:

processMyList(List(1,2,3)) // 6
processMyList(List("Scala ", "is ", "awesome")) // "Scala is awesome"
processMyList(List(true, true, false)) // ERROR

--

--

Kumar Nellipudi

Exploring emerging technologies, Exploring problem solving