0

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")
    };
}
David Aleksanyan
  • 2,953
  • 4
  • 29
  • 39
  • 1
    No, your example works just fine if the class isn't abstract. It needs to be open (and abstract classes are automatically open), but that has nothing to do with companion objects. – Alexey Romanov Sep 23 '18 at 14:23
  • Good point, yes making the class open works also, but why not regular closed classes? :) – David Aleksanyan Sep 23 '18 at 16:24
  • Because you are extending it. That's what open class means: that you can extend it. – Alexey Romanov Sep 23 '18 at 16:33
  • I understand what open class means and that we can add multiple interfaces inside a companion object, but still didn't find out the wider purpose of this capability... – David Aleksanyan Sep 23 '18 at 16:39

1 Answers1

2

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?

Yuri Schimke
  • 12,435
  • 3
  • 35
  • 69