Object Oriented Programming in Scala- 1

Scala uses both Object oriented and functional programming concepts. For folks coming from the Java, we would always explore how to do OOP in Scala. Here I thought of writing few posts related to OOP in Scala (may be a Series of posts ;)). In this post lets talk about-

  • Classes
  • Objects
  • Constructors
  • Overloaded Constructors

Classes:
Like in Java, classes in Scala are also declared using the key word- class.

class Person{
}

Lets give some fields and methods for this class. So the fields can be declared as either- var’s and val’s (Read about their difference here). And the methods are declared using the keyword- def. Java programmers might note this difference in method declaration. The method names can be same as long as their full signatures(type name, list of parameters with types and the return) must be unique- what we would call as Overloading. So the enhanced version of the class:

class Person{
  var firstName = "Mohamed"
  var lastName = "Sanaulla"
  override def toString:String= firstName+" "+lastName
}

So I have added 2 fields- firstName and lastName. In Scala- if no access level is specified, then its public. So lets try to create an instance of this Person.

scala> var person2 = new Person
person2: Person = Mohamed Sanaulla

scala> person2.firstName
res2: java.lang.String = Mohamed

scala> person2.lastName
res3: java.lang.String = Sanaulla

scala> person2.firstName = "FirstName"

scala> person2.lastName = "LastName"

scala> println(person2.firstName)
FirstName

scala> println(person2.lastName)
LastName

So we can see that we use the same- “new” operator to create an instance. As we don’t have a constructor we are not passing any values while creating the instance. Also we are able to get and set the values of the fields. And the methods in a scala Class are declared with the key word def. In the above code you can also see another keyword being used: override– This is to indicate that its an overridden version of toString().

Coming to another important difference in Scala- classes cannot have static members. Those members supposed to be static are added in a special construct called “Singleton Object“- which means- Only One Object of that type. We cannot use new for Singleton Objects. Lets take a look at an example:

object MySingletonObject{
  var count=100
  def getCount = count
}

So how do we use this?

scala> MySingletonObject.getCount
res0: Int = 100

See we havent used the new to create an instance of a Singleton Object.
Lets peek at the class file generated for Person-

C:devscalablogPost>javap Person
public class Person extends java.lang.Object implements scala.ScalaObject{
    public java.lang.String firstName();
    public void firstName_$eq(java.lang.String);
    public java.lang.String lastName();
    public void lastName_$eq(java.lang.String);
    public java.lang.String toString();
    public Person();
}

So you can see there’s a geter, a setter having the name same as that of the name of the field. Scala doesnt use JavaBeans naming convention for the getters and setters. Looking at the class file for the Singleton Object:

C:devscalablogPost>javap MySingletonObject
Compiled from "OOP1.scala"
public final class MySingletonObject extends java.lang.Object{
    public static final int getCount();
    public static final void count_$eq(int);
    public static final int count();
}

You can see that internally it has generated static members. And for var fields- there’s a setter method generated as: _$eq and this allows the programmer to set the values for the var field (which is public).

In the Person class- the fields are public. Lets have a look at how we can use Constructors and increase the level of hiding for the fields.
Unlike Java, constructors in Scala are bit different. In Scala you have two types of constructors- primary and auxiliary constructors. The primary constructors comprise the complete class declaration. Lets have a look at how we can modify the Person class to support constructor.

class Person(firstName:String, lastName:String){
  override def toString():String = firstName+" "+lastName
}

In the above example we have primary constructor taking 2 String parameters. Lets look at the class file generated before explaining further:

C:devscalablogPost>javap Person
Compiled from "OOP1.scala"
public class Person extends java.lang.Object implements scala.ScalaObject{
    public java.lang.String toString();
    public Person(java.lang.String, java.lang.String);
}

So you can see that there’s no methods generated for setting or getting these parameter fields. This is because by default the parameters in the constructors are declared as private val. How do we create an instance of Person then?

scala> var p = new Person("Mohamed", "Sanaulla")
p: Person = Mohamed Sanaulla

scala> println(p)
Mohamed Sanaulla

So its pretty similar to the way we create an instance in Java. 🙂 Lets play with the parameters of the constructor a bit further-

class Person(var firstName:String, var lastName:String){
  override def toString():String = firstName+" "+lastName
}

The class file generated for this would be:

C:devscalablogPost>javap Person
Compiled from "OOP1.scala"
public class Person extends java.lang.Object implements scala.ScalaObject{
    public java.lang.String firstName();
    public void firstName_$eq(java.lang.String);
    public java.lang.String lastName();
    public void lastName_$eq(java.lang.String);
    public java.lang.String toString();
    public Person(java.lang.String, java.lang.String);
}

So you see with constructor parameters becoming var, the compiler automatically generates the methods to access and set these values. We can make them private and var- by preceding the var keyword in the parameter list by: private. And then we can add methods to get the values for these parameters. So these parameters of the primary constructor are accessible within the class declaration(provided they are not public).

More about constructors is continued here.

5 thoughts on “Object Oriented Programming in Scala- 1”

Leave a Reply

Discover more from Experiences Unlimited

Subscribe now to keep reading and get access to the full archive.

Continue reading