TExcelTAD
Home › Kotlin › Kotlin Class Functions

Kotlin Class Functions

Properties describe what an object has; member functions (methods) describe what it can do. Member functions are declared inside the class body and can read and change the object's properties.

Declaring member functions

kotlin · try it yourself
class BankAccount(val owner: String) {
    var balance = 0.0

    fun deposit(amount: Double) {
        balance += amount
        println("$owner deposited $amount")
    }

    fun withdraw(amount: Double): Boolean {
        if (amount > balance) {
            println("Insufficient funds for $amount")
            return false
        }
        balance -= amount
        return true
    }
}

fun main() {
    val acc = BankAccount("Lena")
    acc.deposit(100.0)
    acc.withdraw(30.0)
    acc.withdraw(500.0)
    println("Balance: ${acc.balance}")
}
Lena deposited 100.0
Insufficient funds for 500.0
Balance: 70.0

Inside a member function, properties are used by their plain name (balance). Each call works on the object it was called on.

this

this refers to the current object. You need it mainly when a parameter has the same name as a property:

kotlin · try it yourself
class Player(var name: String, var score: Int = 0) {
    fun rename(name: String) {
        this.name = name     // property = parameter
    }

    fun beats(other: Player) = this.score > other.score
}

fun main() {
    val p1 = Player("P1", 40)
    val p2 = Player("P2", 25)
    p1.rename("Kim")
    println("${p1.name} beats ${p2.name}: ${p1.beats(p2)}")
}
Kim beats P2: true

Overriding toString

Every class inherits toString(), equals() and hashCode() from Any. Override toString() to control how objects are printed and used in string templates:

kotlin · try it yourself
class Money(val cents: Long) {
    override fun toString(): String {
        val euros = cents / 100
        val rest = (cents % 100).toString().padStart(2, '0')
        return "€$euros.$rest"
    }
}

fun main() {
    val price = Money(1999)
    println(price)
    println("Total: $price")
}
€19.99
Total: €19.99

Functions that return a new object

A good habit is to make objects immutable (only val properties) and have functions return modified copies instead of changing the original:

kotlin · try it yourself
class Vector(val x: Double, val y: Double) {
    fun plus(other: Vector) = Vector(x + other.x, y + other.y)
    fun scale(f: Double) = Vector(x * f, y * f)
    fun length() = kotlin.math.sqrt(x * x + y * y)
    override fun toString() = "($x, $y)"
}

fun main() {
    val a = Vector(3.0, 4.0)
    val b = Vector(1.0, -1.0)
    println(a.plus(b))
    println(a.scale(2.0))
    println(a.length())
}
(4.0, 3.0)
(6.0, 8.0)
5.0

Operator overloading

Mark a function with operator and a specific name to let your class use symbols such as +, -, *, [] or ==:

kotlin · try it yourself
class Vector(val x: Int, val y: Int) {
    operator fun plus(o: Vector) = Vector(x + o.x, y + o.y)
    operator fun times(k: Int) = Vector(x * k, y * k)
    override fun toString() = "($x, $y)"
}

fun main() {
    val v = Vector(1, 2) + Vector(10, 20)
    println(v)
    println(v * 3)
}
(11, 22)
(33, 66)
Operator Function name
a + b plus
a - b minus
a * b times
a[i] get
a += b plusAssign
-a unaryMinus
a > b compareTo

Tip: Only overload operators when their meaning is obvious (maths types, money, collections). user + group is confusing; user.joinGroup(group) is not.

Infix functions

A member function with one parameter can be marked infix and then called without dot and parentheses, like the built-in to in "a" to 1:

kotlin
class Team(val name: String) {
    infix fun versus(other: Team) = "$name vs ${other.name}"
}
// Team("Red") versus Team("Blue")  ->  "Red vs Blue"

Test yourself

What does this refer to inside a member function?

  1. The class itself
  2. The current object the function was called on
  3. The main function
  4. The parent class

Which keyword is required to override toString()?

  1. open
  2. override
  3. operator
  4. super

Which function name makes a + b work for your class?

  1. add
  2. plus
  3. sum
  4. operatorPlus