Scala Generic Trait

Today is a milestone in theObject Oriented Programmingjourney. In combination withinheritance, that we saw in the past,genericsare a key feature ofObject 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 ourPotatoBag. But, for some reason, we want to describe the action toCombineanything. 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 theCombine[A]trait.

What is calledgenericin this context is the[A]. It means that this will have some kind of type parameter that will be needed atcompiled timeto create the class. For instance, if you were to create aCombine[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 thereducefunction. In this case we usereduceOptionfor safety.reduceOptionwill returnNonewhen the list is empty,reducewill throw an exception.

You can go back to the code and replacereduceOptionbyreduceand remove all items from theTruckOfPotatoesto see it for yourself.

Other thing to try,.reduceOption((a, b) => a.combineWith(b))can be replaced by.reduceOption(_ combineWith _). But, this involveinfixnotation 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