Understanding Classes and its Fields in Scala

For those moving from Java to Scala would find it a bit different to see how the classes and their fields are treated in Scala. Most of you in the Java world always complain about the verbosity of adding fields and then to add their getters and setters. Lets look at how the Classes and its fields in Scala are different from that in Java and how they map to the byte code consumed by the JVM.

We all should know that Scala is like one of the many languages which run on the Java Virtual Machine (JVM). Like Java, Scala is also a statically and strongly typed language. Any code written in Scala gets compiled into the byte code and if then executed by the JVM, so whatever syntactic sugar and constructs Scala provides it all ultimately boils down to creating byte code which can be executed by the JVM.

Classes and Fields in Scala

Let’s take a very simple example of a class in Scala with one field:

class Person{
var name = ""
}

Very concise! But we, the Java developers, would shout at this saying this breaks the encapsulation. Yes, but Scala automatically adds the getters and setters for the fields declared with a var keyword. Lets compile the above class and inspect the byte code using javap

Looking at the above class file generated we can conclude that scala compiler adds getters and setters for the field declared as var. The getters are of the form fieldName() and the setters are of form fieldName_=. As java doesn’t allow the use of = in the method name, $eq is used instead. Lets go ahead and create an instance of this class:

A variable can declared as var or a val. Variables declared as var can be reassigned where as those declared as val cannot be. Read here for more details on their difference. Lets make the name field in the above Person class to val and see the class file generated:

class Person{
val name = "First name"
}

The class file generated gives me only a getter and no setter which is obvious for a field which cannot be reassigned.