Scala Package Objects

So lets talk about this feature most people dont know scala has is the ability to use package objects.

You might dont find that useful since you have do the same with different techniques but i think this is great for the granularity scala have to control visibility.

You can use this feature to create DSL or simple to empower abstractions this feature is compiled so its safe but could lead to bad code if you dont use it with window. Because you can be sharing variables everywhere so this is really useful for module design but  as i sad you need o be careful.

Show me the Code

    Here we have just a simple case class called Fruit and some specializations of the fruit like apple,    plum and banana, all extends from fruit. As you can see there is a package.

Here come the fun the package object object, you need define a name in this case we called this fruits and add some things on it. There is a variable called planted its a List[Fruits] its like a constant. We also have a method that show in console all fruits we have.

Somewhere else you can import that code todo some reuse or DSL if you like it, The magic here is the import at the end of the package as you can see we are importing the fruits._ that means we are adding the val planted and showFruit function as you can see on the code.

This is great to reuse code but you need to have a very strong design todo this otherwise you could endup messing the whole system with coupling but besides that its a cool feature. You can get the whole code on eclipse here.


Popular posts from this blog

Telemetry and Microservices part2

Installing and Running ntop 2 on Amazon Linux OS

Fun with Apache Kafka