Start learning free

LESSON 208 OF 414 · FUNCTIONS & CLASSES

Class Methods in Scala

Lesson Read the full explanation

TL ; DR:

  • A method is a function that lives inside a class. Each object can call its methods, and the methods can read and write the object's fields.


  • Define a method like a regular function, but inside the class body:

    class Dog(val name: String) {
        def bark(): Unit = {
            println("Woof! I am " + name)
        }
    }
    

  • Call it on an object with the dot operator: dog.bark()



Full lesson:

So far you've added data to a class with fields and constructors. The other half of OOP is behavior — actions an object can perform. That's what methods are for.


Defining a method

class Dog(val name: String) {
    def bark(): Unit = {
        println("Woof! I am " + name)
    }
}

The method can directly read the name field. When you call rex.bark(), the method sees rex's name.


Your task

Add a bark() method to Dog that prints "Woof! I am " followed by the dog's name.

Woof! I am Rex
STEP 1 OF 2
    Ctrl + Enter to check

    SCALA · FUNCTIONS & CLASSES

    Class Methods in Scala, explained

    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:

    • def starts a method definition.
    • bark is the name, and the empty parentheses mean it takes no arguments.
    • : Unit is the return type. Unit is 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 in def bark() { ... }. In Scala 3 that doesn't compile: the compiler says '=' expected, but '{' found. Write def bark(): Unit = { ... }.
    • Parentheses are part of the method. A method declared with () must be called with (). Writing rex.bark without them is rejected in Scala 3 with the message method 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 as def legs: Int = 4.
    • A Unit result is (). If you store the result of rex.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 public and no return needed. 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 def inside 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.
    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free