What a method is
Fields give an object data. Methods give it behavior: actions the object can perform. A method is a function defined inside a class. It can read and change the fields of the object it is called on.
Defining a method
A method uses the same def syntax as a function: a name, a parameter list, a return type after a colon, an = sign and a body.
class Dog(val name: String) {
def bark(): Unit = {
println(s"Woof! I am $name")
}
}
Pieces of the declaration:
defstarts a method definition.barkis the name, and the empty parentheses mean it takes no arguments.: Unitis the return type.Unitis Scala's "nothing useful" type, the one a method that only does something, like printing, returns.- The
=sign comes before the body, even when the body is in braces.
The body uses name directly. Inside a method, the fields of the object are in scope without any prefix, so when you call rex.bark(), the method sees rex's name.
Calling a method
Use the dot operator on an object, followed by the method name and its parentheses:
val rex = Dog("Rex")
rex.bark()
This prints:
Woof! I am Rex
Each object runs the method on its own data. A second dog, Dog("Luna"), would print Woof! I am Luna from the same method.
Methods that change state and return values
A method can take parameters and return a value. The result type goes after the parameter list, and the value of the last expression in the body is what the method returns:
class Dog(val name: String) {
var tricks: Int = 0
def learn(): Unit = { tricks += 1 }
def describe(): String = s"$name knows $tricks tricks"
def add(a: Int, b: Int): Int = a + b
}
After rex.learn() has been called twice, rex.describe() returns Rex knows 2 tricks, while Dog("Luna").describe() returns Luna knows 0 tricks, because tricks belongs to each object. And rex.add(2, 3) returns 5.
Methods of the same class can call each other by name. A method that calls bark() inside the class is doing the same as this.bark(), where this is the current object.
Scala details worth knowing
- The
=is required. Older Scala allowed a "procedure syntax" with no equals sign, as indef bark() { ... }. In Scala 3 that doesn't compile: the compiler says'=' expected, but '{' found. Writedef bark(): Unit = { ... }. - Parentheses are part of the method. A method declared with
()must be called with(). Writingrex.barkwithout them is rejected in Scala 3 with the messagemethod bark in class Dog must be called with () argument. By convention, methods that do something are declared with parentheses, and parameterless ones that just return a value can be declared without, such asdef legs: Int = 4. - A
Unitresult is(). If you store the result ofrex.bark(), the stored value is the unit value, written(). It carries no information. - The return type can be inferred for
def describe() = ..., but writing it makes the method's contract clear, and the lesson does so. - No
publicand noreturnneeded. Methods are public by default, and the last expression is the result.
The exercise
The starter code already has Dog(val name: String) and calls rex.bark(). You need to add the method to the class:
class Dog(val name: String) {
def bark(): Unit = {
println(s"Woof! I am $name")
}
}
class Solution {
def mainFunction(): Unit = {
val rex = Dog("Rex")
rex.bark()
}
}
The output is Woof! I am Rex. The s before the string literal enables interpolation, and $name inserts the value of the name field. Without the method, the call fails to compile, because bark is not a member of Dog.
Key takeaways
- A method is a
definside a class, and it can use the object's fields directly. - Declare the return type after the parameters, and put
=before the body. - A method that only performs an action returns
Unit. - Call it with the dot operator, and include the parentheses if the method was declared with them.
