Scala: Part 4: Classes & Objects

This post will focus on basics of OOP in Scala.

Basics

As we all know, Class is a blueprint of object. A simple class with no variables & methods:

scala> class SimpleClass{}
defined class SimpleClass

scala> var obj=new SimpleClass
obj: SimpleClass = SimpleClass@1364ee5

Member variables: Can be defined using var or val.

Methods: Can be defined using the keyword def as used to define functions.

You must provide initial values of variables in the class

scala> class Person {var name}
<console>:1: error: '=' expected but '}' found.
class Person {var name}
                      ^
scala> class Person {var name=""; var age=0}
defined class Person

scala> p.name="Rasesh"

scala> p.age=24

scala> println(p.age)
24

Now, check the difference between var and val in terms of reference to object:

scala> val p1=new Person
p1: Person = Person@18a80d4

scala> p1=new Person
<console>:6: error: reassignment to val
p1=new Person
  ^

You can change the variables in the object pointed by p1 but not the object being pointed by p1.

Default access in Scala is public for the variables defined. To make it private:

scala> class Person {private var name=""; private var age=0}
defined class Person

scala> var p=new Person
p: Person = Person@9578c1

scala> p.name="Rasesh"
<console>:6: error: variable name cannot be accessed in Person
p.name="Rasesh"

You cannot access or change the fields in the object as they are defined private. So, we will need to add getters and setters in the class:

scala> class Person {private var name=""; def getName() : String = {return name}; def setName(nm: String): Unit = {name=nm} }
defined class Person

scala> val p=new Person
p: Person = Person@1450337

scala> p.setName("Rasesh")

scala> println(p.getName())
Rasesh

Unit is similar to void in Scala. If you don’t specify any return value, it is assumed to be a procedure returning no value i.e. Unit.

The values passed as argument in methods are val, and hence cannot be changed. See an example:

scala> class Person {private var name=""; def getName() : String = {return name}; def setName(nm: String): Unit = {nm="new name"} }
<console>:4: error: reassignment to val
class Person {private var name=""; def getName() : String = {return name}; def setName(nm: String): Unit = {nm="new name"} }

The “return” keyword is not mandatory in Scala and in absence of it returns the last value computed by the method.

scala> def f(): Unit = "this string is lost"
f: ()Unit

scala> f

scala> def g() = "this string is not lost"
g: ()java.lang.String

scala> g
res16: java.lang.String = this string is not lost

scala> def h() { "this string is also lost" }
h: ()Unit

scala> h

scala> def g(): String = { "this string is also lost" }
g: ()String

scala> g
res18: String = this string is also lost

Singleton Objects

Scala does not have static members but it has singleton objects. A singleton object definition looks similar to class but with the keyword “object”

object Person{
var staticInt=0
val person=new Person
person.name="Rasesh Mori"
person.age=24

def greetPerson(): String = "Hello "+person.name+" static int: "+staticInt
}

The singleton object’s name is the same as the class defined above.

When a singleton object shares the same name with a class, it is called that class’s companion object. You must define both the class and its companion object in the same source file. The class is called the companion class of the singleton object. A class
and its companion object can access each other’s private members.

Singleton object is similar to home of static fields in Java. I can also hold methods as described in previous object (greetPerson) and it can be accessed as follows:

$ cat person.scala
class Person{
   private var name=""
   private var age=0

   def getName() : String = name
   def setName(nm: String) { name = nm }

   def getAge() : Int = age
   def setAge(ag: Int) {age=ag}
}

object Person{
   var staticInt=0
   val person=new Person
   person.name="Rasesh Mori"
   person.age=24

   def greetPerson(): String = "Hello "+person.name+" static int: "+staticInt
}

Person.staticInt=1
println(Person.greetPerson())

$ scala person.scala
Hello Rasesh Mori static int: 1

Singleton object acts similar to static block in Java and is executed once it is accessed.

A singleton object that does not share the same name with a companion
class is called a standalone object. You can use standalone objects for many
purposes, including collecting related utility methods together.

Scala Application:

To run a Scala program, you must supply the name of a standalone singleton
object with a main method that takes one parameter, an Array[String],
and has a result type of Unit.

Now, we make some changes in previous “person.scala” file and add a new file “runPerson.scala” as follows:

$ cat person.scala 
class Person{
	private var name=""
	private var age=0

	def getName() : String = name
	def setName(nm: String) { name = nm; Person.staticInt=1 }

	def getAge() : Int = age
	def setAge(ag: Int) {age=ag}
}

object Person{
	var staticInt=0
	val person=new Person
	person.name="Rasesh Mori"
	person.age=24

	def greetPerson(): String = "Hello "+person.name+" static int: "+staticInt
}

$ cat runPerson.scala 
object PersonMain {
	def main(args: Array[String]) {
		val p=new Person
		p.setName(args(0))
		p.setAge(args(1).toInt)
		println(p.getName()+" "+p.getAge())
	}
}

Let’s compile them using scalac, Scala compiler:

$ scalac person.scala runPerson.scala

This creates class files for corresponding classes as shown below:

$ ls *.class
Person.class Person$.class PersonMain.class PersonMain$.class

Now, let’s run the application. Don’t be confused looking at class files that it will be interpreted by ‘java’ but there is a special interpreter that we already used, scala

$ scala PersonMain Rasesh 24
Rasesh 24

Ok. Enough for today. Let’s see what we learn new next time.

<= Previous Post

1 thought on “Scala: Part 4: Classes & Objects

  1. Pingback: Scala: Part 3 : Sets & Maps | Rasesh Mori

Leave a comment