Kotlin Class Functions

Class functions, also called methods, define the behavior an object can perform using its own properties.

Defining Member Functions

A member function is declared with the fun keyword inside a class body, just like a top-level function, except it has automatic access to the class's properties. Member functions describe what an object can do.

A Simple Member Function

class Circle(val radius: Double) {
    fun area(): Double {
        return Math.PI * radius * radius
    }
}

fun main() {
    val circle = Circle(3.0)
    println("Area: ${circle.area()}")
}

Using 'this' Inside a Class

Inside a member function, the keyword this refers to the current object instance. It's mostly optional in Kotlin because the compiler resolves property names automatically, but it becomes necessary when a parameter name shadows a property name.

Disambiguating With 'this'

class Wallet(var balance: Double) {
    fun setBalance(balance: Double) {
        this.balance = balance
    }
}

fun main() {
    val wallet = Wallet(10.0)
    wallet.setBalance(250.0)
    println(wallet.balance)
}
Note: Without 'this.balance', the assignment inside setBalance would just reassign the function parameter, leaving the object's actual property unchanged.

Functions That Mutate State

Member functions often update an object's own var properties rather than returning a brand-new value. This is a core OOP idea: behavior and the state it modifies live in the same place.

Mutating Object State

class ShoppingCart {
    var itemCount: Int = 0
    var total: Double = 0.0

    fun addItem(price: Double) {
        itemCount += 1
        total += price
    }
}

fun main() {
    val cart = ShoppingCart()
    cart.addItem(12.5)
    cart.addItem(7.25)
    println("${cart.itemCount} items, total: ${cart.total}")
}
  • Member functions are declared with fun inside a class body
  • They automatically see the class's properties without any extra passing
  • this refers to the current instance and resolves naming conflicts
  • Functions can return computed values or mutate the object's own state
Function StyleExamplePurpose
Computed / purefun area(): DoubleReturns a value derived from properties
Mutatingfun addItem(price: Double)Changes the object's own state
Side-effectingfun printSummary()Performs an action like printing
Note: Keep functions focused on one responsibility - a function that both mutates state and returns an unrelated value is often a sign the class needs to be split.

Understanding member functions sets up the final core concept: inheritance, where classes can share and extend behavior.

Exercise: Kotlin Class Functions

How do you call a member function greet() on an instance named person?