Using Companion Objects as Static Alternatives in Kotlin
📖 Scenario: Imagine you are creating a simple app that needs to count how many times a certain action happens. You want to keep this count shared across all instances of a class without creating separate copies for each object.
🎯 Goal: You will build a Kotlin class with a companion object that holds a shared counter. You will then write code to increase and display this counter, demonstrating how companion objects act like static members.
📋 What You'll Learn
Create a Kotlin class named
ActionCounterInside
ActionCounter, create a companion object with a variable count initialized to 0Add a function
increment() inside the companion object to increase count by 1Add a function
getCount() inside the companion object to return the current countCall
increment() three times and then print the current count using getCount()💡 Why This Matters
🌍 Real World
Companion objects let you keep shared data or helper functions inside a class, similar to static members in other languages. This is useful for counters, constants, or factory methods.
💼 Career
Understanding companion objects is important for Kotlin developers to write clean, efficient code that shares data and behavior without unnecessary object creation.
Progress0 / 4 steps