Introduction
In a previous lesson, you were introduced to classes and objects. We looked at some of Scala’s built-in classes such as Seq. But you can make your own classes and, in this chapter, we will cover user-defined classes and learn how to write our very own classes and objects. We will pick up where we left off in the introductory lesson; it is recommended you go over the lesson once more before moving on.
Without further ado, let’s create our own Person class.
Defining a Class
To define a class in Scala, the class keyword is used, followed by an identifier (class name) of our choosing.
Let’s map the syntax to our Person class.
1
class Person
At this point, our class doesn’t have any properties or methods.
Defining the Properties of a Class
Properties are variables and in Scala, they are called fields. They are also known as instance variables because every instance gets its own set of the variables.
All the members of a class, including fields, are placed in a block.
Our Person class has three fields: name, gender, and age.