Revisiting the Building Blocks: Kotlin Classes and Object-Oriented Essentials

Lesson Overview

Greetings! Today, we're exploring Kotlin classes, the core building blocks of Object-Oriented Programming (OOP) in Kotlin. Through hands-on examples, we'll dive into the fundamental concepts of Kotlin classes, including their structure, properties, and functions.

Kotlin Classes Refresher

Let's begin with an introduction to Kotlin classes. Essential to OOP, Kotlin classes bundle relevant data and functions into compact units called objects. Consider a video game character, which is a typical example of a class instance, with specific properties (such as health or strength) and functions (such as attack or defense).

class GameCharacter(val name: String, var health: Int, var strength: Int) {
    // Function to simulate an attack on another character
    fun attack(otherCharacter: GameCharacter) {
        otherCharacter.health -= this.strength  // Reduces the health of the target character
    }
}

fun main() {
    // Create instances of GameCharacter
    val hero = GameCharacter("Hero", 100, 20)
    val villain = GameCharacter("Villain", 80, 15)

    // Display initial health
    println("${villain.name} initial health: ${villain.health}")

    // Hero attacks Villain
    hero.attack(villain)

    // Display health after attack
    println("${villain.name} health after attack: ${villain.health}")
}

/* Output:
Villain initial health: 80
Villain health after attack: 60
*/

Kotlin classes facilitate the grouping of associated code elements, simplifying their management. Now, to better understand how the above example works, let's go through it step by step.

Structure of a Kotlin Class

A Kotlin class serves as a blueprint consisting of properties and functions. While properties represent data relevant to a class instance, functions are actions or operations that manipulate this data. Each class may use a primary constructor to define properties directly.

Kotlin's primary constructor allows you to define properties concisely without requiring additional getters or setters, as they are automatically generated by the language. This concise syntax eliminates boilerplate code often needed in other programming languages, making your classes more readable and easier to maintain.

Kotlin
class GameCharacter(val name: String, var health: Int, var strength: Int)

fun main() {
    val character = GameCharacter("Hero", 100, 20)  // Object or instance of the class
}

In the example above, the name, health, and strength properties are defined directly in the primary constructor and can be accessed or modified without writing additional boilerplate code. This demonstrates Kotlin's powerful and concise syntax for defining classes.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal