0
0
Kotlinprogramming~30 mins

Companion objects as static alternatives in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
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 ActionCounter
Inside ActionCounter, create a companion object with a variable count initialized to 0
Add a function increment() inside the companion object to increase count by 1
Add a function getCount() inside the companion object to return the current count
Call 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
1
Create the Kotlin class with a companion object and count variable
Create a Kotlin class called ActionCounter. Inside it, create a companion object with a variable count initialized to 0.
Kotlin
Need a hint?

Use var count = 0 inside the companion object to hold the shared count.

2
Add increment and getCount functions inside the companion object
Inside the companion object of ActionCounter, add a function increment() that increases count by 1, and a function getCount() that returns the current value of count.
Kotlin
Need a hint?

Define increment() to add 1 to count. Define getCount() to return count.

3
Call increment three times using the companion object
Call ActionCounter.increment() three times to increase the shared count.
Kotlin
Need a hint?

Call ActionCounter.increment() exactly three times in main().

4
Print the current count using getCount
Add a println statement to print the current count by calling ActionCounter.getCount().
Kotlin
Need a hint?

Use println(ActionCounter.getCount()) to show the count.