Start learning free

LESSON 184 OF 348 · OBJECT-ORIENTED PROGRAMMING

Class Methods in Scala 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 {
        public var name: String = ""
    
        def bark() {
            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 {
    public var name: String = ""

    def bark() {
        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

    Class Methods in Scala

    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free