Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access methods outside companion object - Kotlin

I'm pretty new to kotlin and I was wondering if it's possible, and if it's against best practice to access methods and variables that are outside a companion object, from within the companion object.

For example

class A {
    fun doStuff(): Boolean = return true

    companion object{
        public fun stuffDone(): Boolean = return doStuff()
    }
}

or something like that

Thank you

like image 719
alessandro gaboardi Avatar asked Apr 03 '17 07:04

alessandro gaboardi


People also ask

How do you override a companion object in Kotlin?

What you can do is to subclass the parent and add a new companion object that has a method with the same name as the parent and call the parent method from inside. Static methods can't be overridden. It's called shadowing as you hide a method with another one.

How do you access companion object in another class Kotlin?

In Kotlin, we can easily create a thread-safe singleton using the object declaration. If we declare the object inside a class, we have an option to mark it as a companion object. In terms of Java, the members of the companion object can be accessed as static members of the class.

How do you call a method inside a companion object in Kotlin?

However, in Kotlin, you can also call callMe() method by using the class name, i.e, Person in this case. For that, you need to create a companion object by marking object declaration with companion keyword.

What is the point of a companion object in Kotlin?

Answer: Companion object is not a Singleton object or Pattern in Kotlin – It's primarily used to define class level variables and methods called static variables. This is common across all instances of the class.


2 Answers

doStuff() is an instance method of a class; calling it requires a class instance. Members of a companion object, just like static methods in Java, do not have a class instance in scope. Therefore, to call an instance method from a companion object method, you need to provide an instance explicitly:

class A {
    fun doStuff() = true

    companion object {
        fun stuffDone(a: A) = a.doStuff() 
    }
}
like image 74
yole Avatar answered Oct 21 '22 16:10

yole


You can also call functions that are outside of companion object block.

class A {
    fun doStuff() = true

    companion object {
        val a = A()
        fun stuffDone() = a.doStuff() 
    }
}
like image 2
Uddhav P. Gautam Avatar answered Oct 21 '22 15:10

Uddhav P. Gautam