Methods in Kotlin

Kotlin supports methods defined on class types.

import kotlin.math.times

class Rectangle(val width: Int, val height: Int) {
    // This `area` method is defined on the Rectangle class.
    fun area(): Int {
        return width * height
    }

    // Methods can be defined for either the class itself or its companion object.
    // Here's an example of a method defined on the class.
    fun perimeter(): Int {
        return 2 * width + 2 * height
    }
}

fun main() {
    val r = Rectangle(width = 10, height = 5)

    // Here we call the 2 methods defined for our class.
    println("area: ${r.area()}")
    println("perimeter: ${r.perimeter()}")

    // Kotlin handles method calls on both the object and its reference similarly.
    // There's no need for explicit pointer dereferencing.
    val rRef = r
    println("area: ${rRef.area()}")
    println("perimeter: ${rRef.perimeter()}")
}

To run the program:

$ kotlinc methods.kt -include-runtime -d methods.jar
$ java -jar methods.jar
area: 50
perimeter: 30
area: 50
perimeter: 30

In Kotlin, classes and their methods are the primary way to structure code. Unlike Go, Kotlin doesn’t have a separate concept of structs and methods. Instead, methods are always associated with classes.

Kotlin doesn’t distinguish between value and pointer receivers as Go does. The language handles object references and method dispatch internally, so you don’t need to worry about whether you’re dealing with an object or a reference to an object when calling methods.

Kotlin also provides properties, which can replace simple getter and setter methods, making the code more concise and idiomatic.

Next, we’ll look at Kotlin’s mechanism for defining abstract types and behaviors: interfaces.