Objects, Continued

Created By: Geoffrey Challen
/ Updated: 2022-05-23

Next we continue our exploration of Kotlin objects. Objects combine state and behavior. Yesterday we showed how they can store data like variables. Now we'll show how they can run algorithms like methods.

Object Methods

Yesterday we began experimenting with simple Kotlin objects. Consider an object that stores information about a room:

Our Room class allows us to model a Rooms height, width, and name. Let's create a few instances!

Cool! But we said that Kotlin objects combine state and behavior. Where's the behavior?

To start, let's see if we can have each room print out the String that we printed manually in the previous example. We'll go through how to do that together.

Show how to implement the formatted print method from the previous walkthrough using an instance method.

Show how to complete the homework problem above. Feel free to cover multiple approaches!

Instance Methods

What we've created above is called an instance method. In some ways it's just like the other methods that we've written. But, because it is part of a class definition, it is also different.

Specifically, instance methods have access to the values of instance variables or properties. We saw that in the walkthrough above, since our print function could access that room's width, height, and name. Let's continue exploring this together, and look at how instance methods can both access instance variables and accept parameters.

Implement an instance method that determines whether a piece of furniture will fit into a given room. Discuss how we combine the state stored in the object (instance variables) with state passed to the method through parameters.

Modifying Instance Variables

Instance methods can both access and modify instance variables. Let's look at example of how that works.

Implement a simple method that modifies the properties. Show how they need to be var first. Don't implement a setter or getter, since those are created for us automatically.

Show how to complete the homework problem above. Feel free to cover multiple approaches!

More Practice

Need more practice? Head over to the practice page.