Nested Objects and Classes

In the previous chapter, we saw the use of a companion object. This is a special scenario for nested objects, where we have object values as properties of a class.

Not only can a class have nested objects, but it can have nested classes, where we have one class defined inside of another one.

Nested Objects

We saw companion object in the previous chapter:

class Thingy {
  companion object {
    fun doSomething() {
      println("Ummm... is this something?")
    }
  }

  // TODO add other properties and functions
}

fun main() {
  Thingy.doSomething()
}

The value of the companion keyword is that functions on the companion object can be called just like you might call static functions in Java:

Thingy.doSomething()

However, you can use the object keyword for nested objects without necessarily using companion.

Named Objects

One option is to give the object a name, akin to how you give a class a name:

class Thingy {
  object Somethingifier {
    fun doSomething() {
      println("Ummm... is this something?")
    }
  }

  // TODO add other properties and functions
}

fun main() {
  Thingy.Somethingifier.doSomething()
}

Then, you reference it via dot notation (Thingy.Somethingifier.doSomething()).

Object Properties

A more typical approach, though, is simply to assign the object to a property, using an object expression as the property initializer:

interface Somethingifier {
  abstract fun doSomething()
}

class Thingy {
  val somethingifier = object : Somethingifier {
    override fun doSomething() {
      println("Ummm... is this something?")
    }
  }

  // TODO add other properties and functions
}

fun main() {
  val thingy = Thingy()

  thingy.somethingifier.doSomething()
}

You can then reference it as you would any other property (thingy.somethingifier.doSomething()).


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.