Back to Blog

Kotlin and Copilot: Add a method to a class

Sandy LaneSandy Lane

Video: Kotlin and Copilot: Add a method to a class by Taught by Celeste AI - AI Coding Coach

Watch full page →

Kotlin and Copilot: Add a Method to a Class

In Kotlin, adding a method to a class is straightforward and enhances the functionality of your objects. This example demonstrates how to define a simple class and add a method that performs an action, such as greeting with the object's name.

Code

class Person(val name: String) {
  // Method to greet using the person's name
  fun greet() {
    println("Hello, my name is $name!")
  }
}

fun main() {
  val person = Person("Alice")
  person.greet()  // Output: Hello, my name is Alice!
}

Key Points

  • Define methods inside a Kotlin class using the fun keyword.
  • Methods can access class properties directly, like name in this example.
  • Calling a method on an instance executes the behavior defined within it.
  • Kotlin’s concise syntax makes adding methods simple and readable.