Scala Generic Trait

Today is a milestone in the Object Oriented Programming journey. In combination with inheritance, that we saw in the past, generics are a key feature of Object Oriented Programming.

Once you start using it, you will never be able to live without it !

I heard the Internet likes potatoes !

In this example, we want to sum our PotatoBag. But, for some reason, we want to describe the action to Combine anything. We can describe combine easily, it is the action of taking two elements of the same type and producing a new element of the same type. You can see there that we declared a function with the typed signature: A.combineWith(A) => A.

With this in place, we can now combine anything. Try to go back to the exercise and create a different case class that inherit from the Combine[A] trait.

What is called generic in this context is the [A]. It means that this will have some kind of type parameter that will be needed at compiled time to create the class. For instance, if you were to create a Combine[Int], you can imagine the compiler writing code for you and creating a whole new class :

trait CombineInt {

def combineWith(a: Int): Int


It is an other way to not have to write almost similar code several times.

Keep in mind that this example has been trim down and simplified for this exercise, in production code we would do things slightly differently but I don't want to bring too much at once and confuse you. I am trying to make bite size knowledge pieces.

The combine pattern is use often and not far away from it you will almost always find the reduce function. In this case we use reduceOption for safety. reduceOption will return None when the list is empty, reduce will throw an exception.

You can go back to the code and replace reduceOption by reduce and remove all items from the TruckOfPotatoes to see it for yourself.

Other thing to try, .reduceOption((a, b) => a.combineWith(b)) can be replaced by .reduceOption(_ combineWith _). But, this involve infix notation as well as the placeholder _, so we are going to learn more about it later. But at least, you have been exposed to it.

Reveal more information and clues
Load Exercise