Kotlin Companion Object (under a minute)

Alex Manhooei
1 min readDec 28, 2022

A companion object is a powerful ally that lives inside a class, like a superhero living inside their secret lair. It’s like a sidekick who knows all the secrets and special abilities of the class, and can use them to help you fight crime and save the day.

For example, let’s say you have a class called SuperSuit, which represents a special suit that gives you superpowers. You might make a companion object to help you activate and deactivate the suit. You could write it like this:

class SuperSuit {
companion object {
fun activate() {
// code to activate the suit
}

fun deactivate() {
// code to deactivate the suit
}
}
}

Now you can use the activate and deactivate functions from the companion object to turn your powers on and off, like this:

SuperSuit.activate()
SuperSuit.deactivate()

So a companion object is like a trusty sidekick, always there to help you harness the full power of your class and become a superhero!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Alex Manhooei
Alex Manhooei

Written by Alex Manhooei

Staff Software Engineer @ Google. All of my blog posts are my personal opinions and not related to my work at google in any shape or form.

Responses (1)

Write a response