Wednesday, August 17, 2016

DSL example with Scala

As you know I just started to learn Scala few months ago, and I have to say that each time I am developing in Scala I see in it a lot of powerful utilities.

 Today I want to implement a simple DSL (Domain Specific Language).

Imagine we want to design a language to communication our software with an external hardware, in this case a robot. We are going to be able to communicate with our robot in this way:


There are some key concepts applied in the code showed above:

  • Syntax sugar. In Scala there are several situations where ',' and '()' are optionals. For example when the method has only one parameter.
  • Builder pattern. To make a fluent Api you can use the Builder pattern which consists in return the object 'this', then in this way, you can concatenate the calls to the different methods in one line. 
  • Implicit conversions. Implicit Conversions are a set of methods that Scala tries to apply when it encounters an object of the wrong type being used. To use implicit conversions, you need to import the class that contains the implicit methods to do the conversions.
The main application.

The Robot class.

Finally the Speed class that enriches the Int type.
You can find all the code in the my github account here