Member Functions

Now let’s explore how to add even more functionality to our classes with functions. A function declared within a Kotlin class is known as a member function.

Member functions possess the same qualities and abilities as the user-designed functions you’ve learned about in the previous lesson. The syntax is the same as well. Some things to keep in mind:

  • When an instance of a class is created, the object has access to any and all functions that exist within the class body.
  • Unlike the code within the init block which executes automatically, the code within the functions will only execute when the function is called.

For example,

class Cat(val name: String, val breed: String) { fun speak() { println("Meow!") } }

We’ve created a simple class, Cat, with a primary constructor and a single member function. We can now create an instance of the class as so and call the speak() function:

var myCat = Cat("Garfield", "Persian") myCat.speak() // Prints: Meow!




Inspect the class, Dog, on the right. Inside the init block, we looped through the list property, competitionsParticipated. Now, let’s add a member function below the init block that shows off one of the dog tricks done in the competition.

Add a member function called, speak(), that outputs the following text:

[name] says: Woof!

Create an instance of the Dog class within the main() function. Call the instance, maxie. Pass in the following custom values for the properties:

  • name: "Maxie"
  • breed: "Poodle"
  • list of competitions should include "Westminster Kennel Club Dog Show" and "AKC National Championship"

Run your code. Then, call the speak() function on maxie on the following line.

Folder Icon

Take this course for free

Already have an account?