Scala Class Fields and Methods
A method is a def that lives inside a class and works with that value's fields. A class value can hold data and do work with it.
A var field can change
The age field is marked var, so a new value can be stored in it. The name field stays as it was.
class Dog(val name: String, var age: Int)
@main def main(): Unit =
val rex = Dog("Rex", 3)
rex.age = 4
println(rex.age)
println(rex.name)A method reads the fields
The label method sits inside the class and reads name and age directly. It is defined and called with no parentheses.
class Dog(val name: String, var age: Int):
def label: String = s"$name is $age"
@main def main(): Unit =
val rex = Dog("Rex", 3)
println(rex.label)Methods can take values and change fields
The ageIn method takes a number of years and adds it to the age. The haveBirthday method changes the stored age itself.
class Dog(val name: String, var age: Int):
def ageIn(years: Int): Int = age + years
def haveBirthday(): Unit = age += 1
@main def main(): Unit =
val rex = Dog("Rex", 3)
println(rex.ageIn(2))
rex.haveBirthday()
println(rex.age)Example
class Cat(val name: String, var age: Int):
def label: String = s"$name, age $age"
def addYears(years: Int): Unit = age += years
def futureAge(years: Int): Int = age + years
@main def main(): Unit =
val miso = Cat("Miso", 2)
println(miso.label)
miso.addYears(3)
println(miso.label)
println(miso.futureAge(10))Key points
- Var field: a field marked var can be given a new value after the value is created.
- Val field: a field marked val cannot be given a new value.
- Method: a def inside a class, which can read the fields of its own value directly.
- Method parameter: a value passed into a method in parentheses, which the method uses in its work.
- No parentheses: a method with no parameters and no changes is written and called without parentheses.
- Unit method: a method marked Unit does work, such as changing a var field, and gives back no value.
In this example, the Cat class holds a name and a var age, and its label method builds a line from both fields. The addYears method raises the stored age from 2 to 5, so the second label shows 5. The futureAge method adds 10 to the current age and gives back 15 without changing the stored age.
Note
a no-parentheses method is called the same way a field is read, with no parentheses after its name.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
A Dog value starts with age 3. Its haveBirthday method adds 1 to the age field. What is the age after haveBirthday is called once?