Skip to main content
Android Development with Kotlin
CHAPTER 06 Beginner

Functions and Object-Oriented Programming in Kotlin

Updated: May 16, 2026
25 min read

# CHAPTER 6

Functions and Object-Oriented Programming in Kotlin

1. Introduction

In Chapter 3, we wrote a basic function to print a welcome message. But real software engineering requires functions that can accept input, calculate data, and return answers. Furthermore, as an application grows, managing hundreds of floating variables and functions becomes impossible. We need to group related data and actions together. This is the foundation of Object-Oriented Programming (OOP). In this chapter, we will master Functions and OOP in Kotlin. We will build dynamic functions with parameters and return types, construct blueprints using Classes, instantiate Objects, and explore Kotlin's highly efficient Data Classes.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Pass data into functions utilizing Parameters.
  • Extract calculated data out of functions utilizing Return Types.
  • Understand the core principles of Object-Oriented Programming.
  • Define a Class blueprint and instantiate Objects from it.
  • Implement Class Inheritance.
  • Utilize Kotlin Data Classes to structure complex application data.

3. Advanced Functions (Parameters)

A basic function fun jump() just does one thing. What if we want to tell the computer *how high* to jump? We use a Parameter.
kotlin
12345678910
// 'height' is a Parameter of type Int
fun jump(height: Int) {
    println("The character jumped $height feet in the air!")
}

fun main() {
    // We 'pass an Argument' (10) into the function!
    jump(10)
    jump(50) 
}

4. Advanced Functions (Return Values)

Functions shouldn't just print things; they should calculate answers and hand them back to us. To do this, we specify a Return Type using a colon :, and use the return keyword.
kotlin
1234567891011
// This function MUST hand back an Int!
fun calculateArea(width: Int, height: Int): Int {
    val total = width * height
    return total // Handing the answer back!
}

fun main() {
    // We capture the returned answer inside a variable!
    val roomArea = calculateArea(10, 5)
    println("The room is $roomArea square feet.")
}

5. Object-Oriented Programming (Classes & Objects)

Imagine building a car racing game. You need 50 cars. Instead of creating 150 separate variables for car1Color, car1Speed, car2Color, etc., you create a blueprint called a Class.
kotlin
123456789101112131415161718
// The Blueprint (Class)
class Car(var color: String, var topSpeed: Int) {
    
    // A function inside a Class is called a 'Method'
    fun drive() {
        println("The $color car is driving at $topSpeed mph!")
    }
}

fun main() {
    // Instantiating Objects from the Blueprint!
    val ferrari = Car("Red", 200)
    val batmobile = Car("Black", 300)
    
    // Triggering their internal methods
    ferrari.drive()
    batmobile.drive()
}

6. Inheritance

What if you want to create an ElectricCar? It shares properties with Car, but has a battery. You don't rewrite the whole class; you Inherit from it. *(Note: In Kotlin, classes are locked by default. You must add the open keyword to allow inheritance!)*
kotlin
12345678910111213141516171819
// The 'open' keyword allows other classes to inherit this blueprint!
open class Vehicle(var wheels: Int) {
    fun startEngine() {
        println("Vroom!")
    }
}

// ElectricCar INHERITS from Vehicle using the colon ':'
class ElectricCar(wheels: Int, var batteryLevel: Int) : Vehicle(wheels) {
    fun charge() {
        println("Charging battery to 100%...")
    }
}

fun main() {
    val tesla = ElectricCar(4, 50)
    tesla.startEngine() // Inherited from Vehicle!
    tesla.charge()      // Specific to ElectricCar!
}

7. Interfaces

An Interface is a strict contract. If a class signs the contract (implements the interface), it *must* write the code for the functions listed in the contract.
kotlin
1234567891011
// The Contract
interface Clickable {
    fun onClick()
}

// The Button class MUST implement the onClick function!
class Button : Clickable {
    override fun onClick() {
        println("Button was successfully clicked!")
    }
}

8. Data Classes

In Android, you constantly download data (like a User profile) from the internet. Kotlin provides a massive shortcut for creating classes that purely hold data, called a Data Class. It automatically generates helpful background functions (like printing and copying) without you writing them.
kotlin
12345678910
// The 'data' keyword does all the heavy lifting!
data class User(val id: Int, val username: String, val email: String)

fun main() {
    val playerOne = User(1, "DragonSlayer", "dragon@test.com")
    
    // Data classes print beautifully automatically!
    println(playerOne) 
    // Output: User(id=1, username=DragonSlayer, email=dragon@test.com)
}

9. Common Mistakes

  • Forgetting the return Keyword: If you define a function with a return type (e.g., fun getScore(): Int), the Kotlin compiler will throw a fatal error if you forget to actually write return 100 inside the block. The contract must be fulfilled.
  • Forgetting open: In Java, all classes can be inherited by default. In Kotlin, they are "final" (locked). If you try to inherit from a standard class Car, it will crash. You must explicitly declare open class Car.

10. Best Practices

  • Single Responsibility Principle: A Class should do one thing, and do it well. Do not create a User class that holds their email, calculates their taxes, downloads images from the internet, and plays a sound effect. Break those into separate classes (User, TaxCalculator, NetworkManager).

11. Exercises

  1. 1. Write a function named multiply that accepts two Int parameters, multiplies them together, and returns the Int result.
  1. 2. Create a data class named Product that holds a name (String) and a price (Double).

12. Coding Challenges

Challenge: Build a miniature RPG combat system.
  1. 1. Create a class called Player with properties name (String) and health (Int).
  1. 2. Create a method inside Player called takeDamage(amount: Int). It should subtract the amount from health.
  1. 3. In main(), instantiate a Player named "Arthur" with 100 health. Call takeDamage(20), then print Arthur's current health.

13. MCQ Quiz with Answers

Question 1

In Kotlin, if a developer wishes to create a "Blueprint" template to generate 50 identical enemies in a video game, which architectural structure must they define?

Question 2

What specific keyword must be prepended to a Kotlin class declaration to allow other child classes to inherit its properties and methods?

14. Interview Questions

  • Q: Explain the structural and functional differences between a standard Kotlin class and a data class. In what specific Android scenario is a data class the mandatory choice?
  • Q: Describe the concept of Class Inheritance. Why does Kotlin require the explicit open modifier, unlike Java?
  • Q: Contrast a Class with an Interface. Why can a Class implement multiple Interfaces, but only inherit from one parent Class?

15. FAQs

Q: Can I put multiple classes in one file? A: Yes, Kotlin allows you to define multiple classes in a single .kt file. However, for large projects, best practice is to put one major class per file (e.g., User.kt, Car.kt) to keep the codebase organized.

16. Summary

In Chapter 6, we elevated our code from simple scripts to robust architectures. We mastered the mechanics of data flow, passing variables into functions as Parameters and extracting results via Return Types. We embraced the paradigm of Object-Oriented Programming (OOP), defining structural Classes and instantiating dynamic Objects in memory. We implemented Inheritance to share logic, defined strict architectural contracts using Interfaces, and leveraged Kotlin's highly optimized Data Classes to cleanly model complex application payloads.

17. Next Chapter Recommendation

We can now create a single User object. But what if we need to store 1,000 users downloaded from a database? Proceed to Chapter 7: Collections and Null Safety in Kotlin.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·