Sunday, July 31, 2016

Fast Scala: Constructing a Rational

Today I am going to summarize the chapter 6 of the Programming in Scala book of Martin Odersky. This chapter guide you through several technical aspects of Scala, implementing a real example. In concrete implementing the class Rational.

 A specification for class Rational

A rational number is a number that can be expressed as a ratio n/d, where n and d are integers, except that d cannot be zero

Constructing a Rational

Note that the Scala compiler will compile any code you place in the class body, which isn't part of a field or a method definition, into the primary constructor. In our case, every time you construct a Rational a message "My Rational is created" will be printed.

Another interesting thing is the 'require' method. The 'require' method takes one boolean parameter. If the passed value is true, require will return normally. Otherwise, require will prevent the object from being constructed by throwing an IllegalArgumentException. The require method belongs to the Predef object which is imported by default by the Scala compiler.

Finally we added an implementation of the toString method. By default the toString method prints the memory location where lives the object in the heap.

Adding Rationals

For example, to add 1/2 + 2/3, you multiply both parts of the left operand by 3 and both parts of the right operand by 2, which gives you 3/6 + 4/6. Adding the two numerators yields the result 7/6.


Note that we added two fields named num and denom, and initialized them with the values of class parameters n and d. This is because you cannot access in this way : that.n or that.d, because n and d are in scope in the code of your + method, you can only access their value on the object on which + was invoked.

With our defined method +. You can write code like that: x + y , where x and y and rational objects.
And is equivalent to write that: x.+(y). Of course, write x + y is more natural instead of write something like x.add(y)

Another thing to note, is that it would be great do things like that: x + x * y , where x and y are Rationals. Of course is not the same to that : (x + x) * y than that : x + (x * y). Scala has defined by default rules for operator precedence and for this reason, expressions involving + , * and / operations on Rationals will behave as expected.

Auxiliary constructors

Sometimes, you need multiple constructors in a class. In Scala, constructors other than primary constructors are called auxiliary constructors. For example, a rational number with a denominator of 1 can be written more succinctly as simply the numerator. Instead of 5/1, for example, you can just write 5. Therefore instead of write new Rational(5, 1) simply write new Rational(5). But this requires an auxiliary constructor. Auxiliary constructors in Scala start with def this(...).


Method overloading

Now you can add Rationals, but cannot add an Integer and an Rational. For this, we have to overload the method +. Then you could write code like x + 4 , where x is a Rational

Implicit conversions

Now that you can write r + 2, you might also want to swap the operands, as in 2 + r. Unfortunately this does not work  yet. Because the Int class doesn't have any method tu add Rationals.

However, there is a way to solve this problem in Scala. You can  create an implicit conversion that automatically converts integers to rational numbers when needed. The implicit conversion could be in the companion object.

I hope it was interesting for you, I will try to summarize some interesting chapters of Programming in Scala, in the next posts. We keep Scaling!

Sunday, July 24, 2016

5 minutes of Scala: Prefix unary operators

Well, I am reading the book Programming in Scala, and I am discovering new capabilities of this  language. Today I want to talk about unary operators (also called prefix operators).

The only identifiers that can be used as prefix operators are +, -, ! and ~
Then you have to define your method using unary_<here your operator>, and you could invoke that method using prefix operator notation, such as <your operator><your variable>.

I know maybe all of this, is a bit confusing but seeing code all will be more easy.

Imagine, we want to implement our class Color. This class defines a color using three pixels (red, green, blue). Also we want operate with our Color class, and one required operation is the capability to inverting the color. As Java programmer, I would define a method called inverse, and I would call it in this way : myColor.inverse() . It is a good approach, totally acceptable, but here is when the magic of unary operators comes, you can do the same in Scala with this : !myColor


Note the definition of the method using unary_!. Also remember that only there are 4 supported unary operators: +, -, ! and ~


Sunday, July 17, 2016

Sending messages to your Akka Actors from JMX

Lately I was a bit busy learning new technologies like Scala, Akka and changing my mind to start to think in functional way. As I promised, my next posts will be about Scala and all technologies related to this language.

 Today I want to show you how to combine an old friend like JMX with and application done with Akka. Scala runs on the JVM so you have all the tools available in the Java platform. To follow this tutorial, it is necessary to have an idea about what does it means the Actor Model

Also you need to have installed Scala. Please follow this instructions if you don't have any installation. I recommend to you IntelliJ as a development environment, it provides a cool support to work with Scala.

Cool! We are ready to start. Our application is very simple, we are going to create an Actor called Pong, and this actor will be waiting a message from a JMX client. This client will be able to send messages to our actor Pong. If the message sent is "end", Pong will be terminated. Otherwise the message will be stored in memory. From our JMX client, we can ask for the last message received by the actor Pong. Let's see some code.

First of all , our support to code actors with JMX support. Extending this trait the actor will be registered in our MBeanServer automatically using the methods preStart and postStop. Note that method getMXTypeName is an abstract method and is implemented by the child class.

Is time to define our MBean. By convention the MBean is defined with the suffix MBean. Here is the trait that exposes the operations available from our MBean.


Finally the actor Pong implements the trait showed above and extends from our ActorWithJMXSupport.

Then we need a main application to start up the actor Pong.

Ok! The hard work is done. Now you have to start your application passing to the JVM this parameters:

-Dcom.sun.management.jmxremote 
-Dcom.sun.management.jmxremote.port=1617 
-Dcom.sun.management.jmxremote.authenticate=false 
-Dcom.sun.management.jmxremote.ssl=false

At this point, you have the application running with the actor Pong waiting for requests. As you can see the MBean server is listening in port 1617.

Finally executing jmc in a console, the JMX client provided by the jdk, will be opened. Then you can browse in the MBean browser to find our MBean registered. In the tab operations, you can execute the operations defined by the PongMBean. In the next video, you can see this last part clearly.