Search code examples
androidkotlincompanion-object

Using "this" to get class instance within companion scope in kotlin


Hi i was trying to access the parent class instance from its companion scope in (android studio) Kotlin, like

class A{

    companion object{
        val class_instance = this@A
    }
}

but it doesn't work, and it does outside the scope of Companion. is there any way to get it done, if not why?

thanks in advance.


Solution

  • It should be somewhat rare for a class to need a default instance, but it can make sense in certain scenarios. The standard library's Random class has a default instance, and they do this by making its companion object a subclass of Random itself.

    Cases where it makes sense might be for abstract classes that can have customized subclasses, but have a default implementation that is commonly adequate for most needs.

    So for instance, you could make A's companion object a subclass of A like this:

    abstract class A {
        abstract fun saySomething()
    
        companion object: A() {
            override fun saySomething() = println("Hello world")
        }
    }