Kotlin Class Functions

Kotlin Class Functions

Class functions (also called member functions) are functions that belong to a class and define the behavior of objects.
In Kotlin, class functions are clean, concise, and powerful.


1. Basic Class Function

class Person {
fun greet() {
println("Hello!")
}
}

fun main() {
val p = Person()
p.greet()
}


2. Class Function with Parameters

class Calculator {
fun add(a: Int, b: Int): Int {
return a + b
}
}

fun main() {
val calc = Calculator()
println(calc.add(10, 20))
}


3. Class Function with Expression Body

class MathUtil {
fun square(x: Int) = x * x
}

4. Accessing Class Properties in Functions

class User(var name: String) {
fun printName() {
println(name)
}
}

5. this Keyword in Class Functions

Used to refer to the current object.

class Box(var size: Int) {
fun update(size: Int) {
this.size = size
}
}

6. Function Overloading in Classes

Same function name, different parameters.

class Printer {
fun print(value: String) {
println(value)
}

fun print(value: Int) {
println(value)
}
}


7. Visibility Modifiers in Class Functions

class Account {
private fun secret() {
println("Hidden")
}

fun show() {
secret()
}
}

Modifier Access
public Everywhere (default)
private Within class
protected Class & subclasses
internal Same module

8. Open & Override Functions (Inheritance)

Functions are final by default.

open class Animal {
open fun sound() {
println("Animal sound")
}
}

class Dog : Animal() {
override fun sound() {
println("Bark")
}
}


9. Abstract Functions

abstract class Shape {
abstract fun area(): Double
}
class Circle(val r: Double) : Shape() {
override fun area() = 3.14 * r * r
}

10. Companion Object Functions (Static-like)

class Utils {
companion object {
fun show() {
println("Hello")
}
}
}

Usage:

Utils.show()

11. Inline Class Functions

class Logger {
inline fun log(message: () -> String) {
println(message())
}
}

12. Extension Functions (Related to Classes)

fun String.reverseText(): String {
return this.reversed()
}

Usage:

println("Kotlin".reverseText())

13. Real-World Example

class BankAccount(private var balance: Int) {

fun deposit(amount: Int) {
balance += amount
}

fun withdraw(amount: Int) {
if (amount <= balance) {
balance -= amount
}
}

fun getBalance(): Int = balance
}


Summary

  • Class functions define object behavior

  • Support overloading & overriding

  • Visibility modifiers control access

  • Companion objects replace static methods

  • Clean syntax compared to Java

You may also like...