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 toCombine
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 theCombine[A]
trait.
What is calledgeneric
in 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 thereduce
function. In this case we usereduceOption
for safety.reduceOption
will returnNone
when the list is empty,reduce
will throw an exception.
You can go back to the code and replacereduceOption
byreduce
and remove all items from theTruckOfPotatoes
to 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.