Kotlin
Java

Equality and Object Copying
Kotlin

Created By: Geoffrey Challen
/ Updated: 2021-09-21

I'm glad you're back. The last few days were heavy, so today we're going to slow down and integrate. Today we'll discuss object equality and how to make object copies. While these are new, they are largely straightforward applications of things that we already know.

Equality

What does it mean for two things to be the same? On one hand this is a deep epistemological question. But in our computer programs, it has practical importance.

For example, I might have a list of items and want to remove all of the duplicates, or find something. I might require a key of some kind to access some information, and need to be able to tell whether the key you present is the same as the one that is required. These are examples of places in computer code where equality matters.

Kotlin's notion of equality is left up to us, the class designer, to define. Let's look at an example of how.

Demonstrate the common pattern for the equals method.

Note that, in Kotlin, using the == operator represents a call to the equals method on the first class passing the second as an argument:

Any.equals

equals is one of the methods defined by Any. That means, if we don't override equals, our classes inherit the equals method defined by Any. This doesn't do nothing, but it's not particularly useful. Let's see how it works:

Demonstrate the behavior of Any.equals. Show how it does return true when called on the same object, but not on two objects that have the same field contents.

Copying Kotlin Objects

It may surprise you to learn that Kotlin has no built-in way to copy an object. The reasons for this are somewhat out of scope for us at this point. Put simply, objects may have complex internal state that is difficult or impossible to copy. Put another way, not every object may represent something that can be copied.

However, when our objects can be copied we can enable this using a pattern called a copy constructor. Let's look at how to do that together:

Implement a copy constructor on student. Perform a shallow copy and defer a discussion of deep copies until we discuss references.

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

Solution Walkthrough

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

Solution Walkthrough