Thursday, July 10, 2014

Class Parameter Differences Between Scala And Java

Scala has something called class parameter.  In Java there is no such thing as class parameter but we can initialize a class with constructor arguments which look similar to class parameter in Scala.

Let's have a bit more detailed look.

Scala Class Example

We can define a Scala class as follows -

class Person(name : String) {
    def sayHello(){
      println("Hello "+name)
    }
}

Now to run the class after compiling you can do it the following way -

new Person("John").sayHello()

Output should be

Hello John

However in Java if we want to have send some parameter while instantiating the object it would be similar to following -

public class Person {
    String name ;
    Person(String name){
        this.name=name;
    }
    public void sayHello(){
        System.out.println("Hello"+name);
    }
}

while running we can then run in similar manner as

new Person("John").sayHello()

The output should be same as what we got in Scala.

So What are the Differences?

In Java the parameter passed in the constructor can't be used in any other method unless it is assigned to some field or property.  In Scala it is available for use in any other method of the instance directly.  However the parameter value is only available in this particular instance of the class.

Another difference is in Scala class parameter is defined while defining the class name and we do not need a separate constructor unlike in Java.

How to upgrade the Scala Class Parameters to fields or Properties?

Scala class parameters can be upgraded to fields very easily.  We can do that by adding the keywords val or var.

Here are examples -

class Person(var name : String) {
    def sayHello(){
      println("Hello "+name)
    }
}

class Person(val name : String) {
    def sayHello(){
      println("Hello "+name)
    }
}

If you add the val keyword the parameter becomes immutable field and in the byte code you can see a private field with public getter method.

If you add the var keyword the parameter becomes mutable field and in the byte code you can see a private field with public getter and setter methods.

No comments:

Post a Comment