Feeds:
Posts
Comments

Archive for the ‘Scala’ Category

Scala part 2 – properties

In the preceding post of this series we have scratched the surface of the Scala programming language.

Today we will continue to dissect our small first example, before adding more flesh to the bone.

This example was:

package com.jmg.insurance

class Product (insuranceAmount: Int, deductible: Int) {
  val rate = .05
  def premium = insuranceAmount * rate
}

object Main {
  def main(args: Array[String]): Unit = {
    val p1 = new Product(10000, 500)
    println(p1)
  }
}

There is a few little things not explained yet. First, you have probably already guessed that in Scala, like in most object-oriented languages, the members of a class may be of one of this two sorts:

  • a variable (or a value)
  • a method

In Scala, methods start with the keyword def. Think of define or definition.

A variable declaration start with the keyword var, while a value declaration start with the keyword val.

The only difference between a var and a val is that the former is mutable and the latter is not.

If we would try to modify the value of rate after it has been declared, this won’t compile:

package com.jmg.insurance

class Product (insuranceAmount: Int, deductible: Int) {
  val rate = .05
  rate = .06                 // does not compile
  def premium = insuranceAmount * rate
}

But if we change the code like this:

package com.jmg.insurance

class Product (insuranceAmount: Int, deductible: Int) {
  var rate = .05
  rate = .06                 // now it works 
  def premium = insuranceAmount * rate
}

Now it compiles just fine. Of course it is quite a contrived illustration!

So this sentence in Scala: val rate = .05 is roughly equivalent to this Java statement: public final Double rate = .05;

Every method, value or variable in Scala is public by default. Thus, there is no public modifier, but there is a private or a protected one.

For every public value in a class, Scala adds transparently an accessor method of the same name, for example, with this:

package com.jmg.insurance

class Product (insuranceAmount: Int, deductible: Int) {
  val rate = .05
  def premium = insuranceAmount * rate
}

object Main {
  def main(args: Array[String]): Unit = {
    val p1 = new Product(10000, 500)
    println(p1.rate)
  }
}

Since rate is public, we are allowed to called the generated accessor method:

p1.rate

You may wonder what is this construct, starting with object, after the product class declaration?

Your trained Java expert eyes will have guessed that it contains the famous main method, used to bootstrap a program.

In Java, we need to have a class with a static method called main to trigger the execution of a system.

In Scala, there is no such thing as a static method ! But we can define a singleton object by replacing class by object as the first keyword.

This singleton object’s name could be anything instead of Main. However, the bootstrap method, like in Java, must be called main.

It must declare an array of String as its only parameter. Command line parameters are transmitted this way.

Notice that the syntax to declare an array of strings in Scala is:
arrayName: Array[String]
instead of String[] arrayName as in Java.

Compared to Java, there is a lot less “special cases” in Scala. In Java, an array is a special beast, implemented as a language construct. In Scala, an array is just another class from the library.

The class Array is generic. You have to declare which type of elements you want the array to store.

Therefore the syntax is: args: Array[String]. You can read this: declare args as an array of strings.

Now back to the product class example.

package com.jmg.insurance

class Product (insuranceAmount: Int, deductible: Int) {
  var rate = .05
  def premium = insuranceAmount * rate
}

object Main {
  def main(args: Array[String]): Unit = {
    val p1 = new Product(10000, 500)
    p1.rate = .06
    println(p1)
  }
}

If we choose to declare var rate = .05 Scala would add transparently an accessor method (as with the val example ) and a mutator method, allowing us to modify rate from the outside of the class. (see line 11)

I can hear your disagreement ! This is just a blatant violation of the encapsulation principle !

But it is not ! While it looks like if we are changing a variable of the class from the outside, in fact we are just calling a mutator method, automatically generated by the Scala compiler. It is exactly like if we would have written:

package com.jmg.insurance

class Product (var insuranceAmount: Int, deductible: Int) {
  private var internal_rate = 0.05
  def rate = internal_rate
  def rate_= (r: Double) {internal_rate = r}
}

object Main {
  def main(args: Array[String]): Unit = {
    val p1 = new Product(10000, 500)
    p1.rate = 0.06
    println(p1.rate)
  }
}

This time, we have defined a private variable and named it internal_rate. Then we have defined two public methods, one named rate to return the variable value and the other rate_=(r: Double), the mutator. Ending a method name with _= , like rate_= is the way to declare a mutator method that will be called like this: rate = 0.06. Notice that is just syntactic sugar, We can also call it like this: rate_=(0.06) but the first form is much more interesting, isn’t it?

Notice that with implicit or explicit definition of the methods, the client code is the same. It means that you can safely use the simplest form, the implicit definition and, later on, if you want to react at the property changing event and validate for example that this property modification is not breaking your object integrity, you can switch to the explicit definition of the two methods, and the client code won’t be affected.

Read Full Post »

Scala first steps

I thought that Java would have been my last programming language, but Scala came and I love it!

I tried some dynamic languages like Ruby and was, at a certain point in time, inclined to drop the static typing that I believed so much in, for the conciseness and flexibility of such languages.

But with Scala you don’t have to sacrify anything. You may have the best of both worlds !

In this series of posts, I’ll try, through a small example, to show the flexibility, conciseness and elegancy of this nice language. At the same time, I will demonstrate the Scala way of handling a kind of “multiple inheritance”, without the drawbacks that this technique usually implies.

I will use the insurance business domain as base of this example. Of course, it will not be representative of a real business problem but hopefully will permit to illustrate some of the most pleasant and powerfull features of Scala.

I assume the reader have a good understanding of OO concepts and a working experience with Java, as Scala will be presented as the future of Java or a “better Java”. But no previous exposure to functional programming is required as I will introduce the basic concepts as needed.

The goal is not to teach a complete Scala course but to give you the taste of it. Then if you like it, buy Martin Odersky’s book and learn it in depth, it is worth the effort !

So, let’s start by writing of few lines of code.

Suppose we want to represent an insurance product, with some characteristics, like insurance amount, deductible, premium rate, etc. We could start with something like this:

package com.jmg.insurance

class Product (insuranceAmount: Int, deductible: Int) {
  val rate = .05
  def premium = insuranceAmount * rate
}

object Main {
  def main(args: Array[String]): Unit = {
    val p1 = new Product(10000, 500)
    println(p1)
  }
}

The first line indicates that the class contained in this source file will be included in the package com.jmg.insurance

This is very similar to Java so far, but we will see that the Scala packaging system is more coherent and powerful than its Java counterpart.

Next, we see the definition of the class Product.

class Product (insuranceAmount: Int, deductible: Int)

Notice the parameters in parenthesis. These are the parameters of the primary constructor. Look further down, you will see the call to this constructor:

new Product(10000, 500)

Both parameters, the insurance amount and the deductible are declared of type integer. In Scala, like in Pascal or Eiffel we declare the identifier first, followed by a colon and the type, like:

insuranceAmount: Int

Java, in contrast follows the “C” tradition of putting the type first, followed by the identifier, like:

Integer insuranceAmount

It may be a little disturbing for you at first. Personally I was so used to the Java/C way that I forgot that years ago I felt the Eiffel/Pascal choice much more natural. Any way, this is a question of taste and habits. But there was a better reason for the Scala designers to adopt this syntax: the type inference. In Scala, you will see that we can skip the type declaration very often. Then it is easier for the compiler, when the optional part, the type, is at the end of the sentence.

Now a word about the type itself. In Java, you have two types for integers : int and Integer.

As you know, the former is the primitive type and the latter is a wrapper, allowing to see an integer as an object. There is no such duality in Scala. There is only one integer type Int. You can see it as an real object in all circumstances. You can call methods on it for example. The compiler is taking care of transforming this object in the platform’s primitive type when appropriate.

Now look again at the declaration of the class product:

class Product (insuranceAmount: Int, deductible: Int) {
...
}

I mentioned before that the parameters were the primary constructor’s ones. You may wonder where is the body of this constructor itself?

In fact, in Scala, the body of a class contains the methods, value declarations, plus the constructor’s body. In our example, this constructor is just empty !

It is closed to what is called a Java initialize block, like this:

package com.jmg.insurance;

class MyClass {
    private int someField;
    {
        [init block is here ...]
    }

Except that this Java initialize block is not really part of a constructor, so there is no way to use any constructor’s parameters.

So what happened to the parameters we are receiving when the constructor is called? Don’t we have to store them somewhere for later usage?

This is one of the magic thing that Scala does automatically for you. The constructor’s parameters are automatically available in all the methods of the class and are immutable.

So, this class declaration if roughly equivalent to this Java class.

package com.jmg.insurance;

class Product {

    private final Integer insuranceAmount;
    private final Integer deductible;
    private Double rate = .05;

    Integer getPremium() {
        return new Double(insuranceAmount * rate).intValue();
    }

    public Product(Integer insuranceAmount, Integer deductible) {
        this.insuranceAmount = insuranceAmount;
        this.deductible = deductible;
    }
}

This is equivalent to these lines of Scala code:

package com.jmg.insurance

class Product (insuranceAmount: Int, deductible: Int) {
  val rate = .05
  def premium = insuranceAmount * rate
 }

While it is true that conciseness is not everything, I think that Scala designers have captured here the essence of a very common use case: instantiating a class with a constructor and passing parameters to it. It relieves you from a lot of repetitive plumbing. And it is not finished!

In both the Scala and Java example above, you don’t have access, from outside of the class, to the values passed as parameters and now stored in this instance. For example, in some Java client code, this wouldn’t compile of course:

new Product(10000, 500).insuranceAmount

insuranceAmount is a private member, so to make it accessible to clients, we have to add an accessor method.

package com.jmg.insurance;

class Product {

    private final Integer insuranceAmount;
    private final Integer deductible;
    private Double rate = .05;

    public Integer getInsuranceAmount() {
        return insuranceAmount;
    }

    Integer getPremium() {
        return new Double(insuranceAmount * rate).intValue();
    }

    public Product(Integer insuranceAmount, Integer deductible) {
        this.insuranceAmount = insuranceAmount;
        this.deductible = deductible;
    }
}

Now clients can do this :

new Product(10000, 500).getInsuranceAmount();

To get the same thing in Scala, you just have to put the keyword val in front of the parameters for whom you want to have public access.

package com.jmg.insurance

class Product (val insuranceAmount: Int, val deductible: Int) {
  val rate = .05
  def premium = insuranceAmount * rate
 }

Now these parameters could be read, but not modified from client code. You could do, for example:

    val p1 = new Product(10000, 500)
    println(p1.insuranceAmount)

Don’t worry for now if you don’t understand yet a few details, like “how come we can write this?”:

println(p1) instead of: SomeObject.println(p1)

There is a lot of short-cuts like this one in Scala, but once you know the mechanics under the hood, it lights up and everything falls in place!

For now, the important thing is that you know what println means and does.

What if you want to be able, not only to read those parameters from client code, but also to modify them?

In Java, you will add another method, a mutator. Its name, by Java beans standards, would be setInsuranceAmount for example.

In Scala, just replace the keyword val in front of the mutable parameter by var

package com.jmg.insurance

class Product (var insuranceAmount: Int, var deductible: Int) {
  val rate = .05
  def premium = insuranceAmount * rate
}

Then you will be able to do the following in your client code:

    val p1 = new Product(10000, 500)
    p1.insuranceAmount = 15000
    println(p1.insuranceAmount)

Now let’s continue looking at our Product class declaration.

The second line: val rate = .05 defines a value (as indicated by the keyword val) and assigns to it the value “.05” which is a floating point value.

We could have written: val rate: Double = .05, but the type inference system seeing the constant “.05” is able to assign automatically the type Double to the identifier rate

The next line: def premium = insuranceAmount * rate is a method declaration. When invoked, this method will return a result of type Double. This result is computed as the product of rate by insuranceAmount

The full and somewhat redundant declaration would be
def premium: Double = insuranceAmount * rate
but again the smart type inference system can deduct from the calculation formula that the result must be of type Double.

In the next article, we will continue to show more and more features of the Scala language as they become necessary to enrich our small example.

Read Full Post »