Sunday, 25 December 2011

Understanding Repr type parameter...

Have you ever wondered why scala collections use the Repr type parameter? I have. Only when I started writing my own library the realisation came.

If you want to have a reusable abstract class/trait, which needs to create instances of the subclasses, then you are probably going to use the abstract factory method pattern.

Let's have a look at the example below:


Make is the abstract factory method. We want it to return something of type USD when called on USD class or something of type EUR when called on instance of EUR class.

In order to tell the type checker what is the right type returned by the make method, we introduce the type parameter Repr which is restricted to be a subtype of CurrencyLike (Repr <: CurrencyLike[Repr]). The concrete class such as EUR needs to set the Repr to itself (ie. EUR), and implement the make method. That way + function which uses make to create an instance of currency returns EUR when called on EUR instance or in turn it returns USD when called on instance of USD class.

I hope it helps!

No comments:

Post a Comment