Extension Methods

// Extension method
fun Student.getAge(): String {
    return this.getName() + " is 20 years old"
}

// Class being extended
class Student {
    fun getName(): String {
        return "John Doe"
    }
}

// Usage
fun main() {
    val student = Student()

    print(student.getAge())
}
Reproducible Code Example

Command to reproduce:

gt.sandbox.checkout.commit 9d495a9 \
&& cd "${GT_SANDBOX_REPO}/gt-kotlin-sandbox" \
&& cmd.run.announce "gradle run"

Recorded output of command:

> Task :app:compileKotlin UP-TO-DATE
> Task :app:compileJava NO-SOURCE
> Task :app:processResources NO-SOURCE
> Task :app:classes UP-TO-DATE

> Task :app:run
John Doe is 20 years old
Deprecated Gradle features were used in this build, making it incompatible with Gradle 9.0.

You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

See https://docs.gradle.org/8.1.1/userguide/command_line_interface.html#sec:command_line_warnings

BUILD SUCCESSFUL in 432ms
2 actionable tasks: 1 executed, 1 up-to-date

Use companion object, add empty companion object if you don't have one in your class.

Follow the code example:

interface OutFactory {
  /**
   * Empty companion object is added to provide a hook-up for writing extension
   * methods on the OutFactory 'class'.
   *
   * Typical extension methods will work on instance, of a class/interface
   * This will allow creation of extension methods for a class. */
  companion object
fun OutFactory.Companion.consoleFactory(): OutFactory {
  return object : OutFactory {
    override fun getOutForClass(classHoldingOut: KClass<*>): Out {
      // Return a console-specific Out implementation
      return SimpleConsoleOut(
        classHoldingOut,
        shouldIncludeElapsedTime = true,
        logLevelProvider = LogLevelProvider.LOG_ALWAYS
      )
    }
  }
}


Children
  1. For_class_not_object
  2. Simple