Nested Interfaces and Abstract Classes

Not only can you nest classes and objects inside of classes, but you can nest interfaces as well:

class Thingy {
  interface Transmogrifier {
    abstract fun transmogrify(): Thingy
  }

  // TODO good stuff here
}

val moggle = object : Thingy.Transmogrifier {
  override fun transmogrify() = Thingy()
}

val thingy = moggle.transmogrify()

Or, if you prefer, you can nest abstract classes:

class Thingy {
  abstract class Transmogrifier {
    abstract fun transmogrify(): Thingy
  }

  // TODO good stuff here
}

val moggle = object : Thingy.Transmogrifier() {
  override fun transmogrify() = Thingy()
}

val thingy = moggle.transmogrify()

Naming works the same as with nested classes and named objects: you reference the nested interface or abstract class based on the outer class name (e.g., Thingy.Transmogrifier).


Prev Table of Contents Next

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