Start learning free

LESSON 289 OF 677 · FUNCTIONS & CLASSES

Class Methods in Scala

Lesson

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