Is a Kotlin Companion Object just a way to add functions from an interface?

1k Views Asked by At

I am reading the Kotlin in Action book and trying to understand Companion Objects better, are there any other uses for Companion Ojbects other than adding method implementations from an interface/abstract class?

I came across a way of instantiating an object which only works if the class is abstract:

fun main(args: Array<String>) {
    Fruit.showColor()
}

class Fruit(val name: String) {
    companion object : Apple()
}

abstract class Apple {
    fun showColor(){
        print("I am an apple")
    };
}
1

There are 1 best solutions below

2
On

My mental model for companion object is language level support for safe singletons. i.e. instead of static methods on a class for Factory or Util methods, you can provide those related methods on the Singleton companion object.

The Companion status gives you a lot of default scoping wins that are similar to the java class with static methods.

Your example seems invalid, because why is the Fruit "singleton" an Apple?