Kotlin: Difference between object and companion object in a class

kotlin object
kotlin companion object vs top level
kotlin companion object vs static
kotlin object vs class
kotlin companion object access class fields
kotlin singleton object
kotlin object reference
object without class kotlin

What is the difference between an object and a companion object in a class in kotlin?

Example:

class MyClass {

    object Holder {
        //something
    }

    companion object {
        //something
    }
}

I already read that companion object shall be used, if the containing parameters/methods are closely related to its class.

But why is there also the possibility of declaring a normal object in the class? Because it behaves exactly like the companion, but it must have a name.

Is there maybe a difference in its "static" (I'm from the java side) lifecycle?

Objects can implement interfaces. Inside a class, defining a simple object that doesn't implement any interfaces has no benefit in most cases. However, defining multiple objects that implement various interfaces (e.g. Comparator) can be very useful.

In terms of lifecycle, there is no difference between a companion object and a named object declared in a class.

Objects and companion objects, A class can only have one companion object, and companion objects can not be and when you call it via an object instance, the override in the object's class a function signature and allowing an inline, anonymous definition of a class that� Kotlin allows you to do something similar with companion objects, which are object s tied to a class, meaning a class can access it's companion object's private functions and properties: class ExampleClass { companion object { // Things that would be static in Java would go here in Kotlin private const val str = "asdf" } fun example () { // I can access private variables in my companion object println ( str ) } }

There are two different types of object uses, expression and declaration.

Object Expression

An object expression can be used when a class needs slight modification, but it's not necessary to create an entirely new subclass for it. Anonymous inner classes are a good example of this.

    button.setOnClickListener(object: View.OnClickListener() {
        override fun onClick(view: View) {
            // click event
        }
    })

One thing to watch out for is that anonymous inner classes can access variables from the enclosing scope, and these variables do not have to be final. This means that a variable used inside an anonymous inner class that is not considered final can change value unexpectedly before it is accessed.

Object Declaration

An object declaration is similar to a variable declaration and therefore cannot be used on the right side of an assignment statement. Object declarations are very useful for implementing the Singleton pattern.

    object MySingletonObject {
        fun getInstance(): MySingletonObject {
            // return single instance of object
        }
    }

And the getInstance method can then be invoked like this.

    MySingletonObject.getInstance()

Companion Object

A companion object is a specific type of object declaration that allows an object to act similar to static objects in other languages (such as Java). Adding companion to the object declaration allows for adding the "static" functionality to an object even though the actual static concept does not exist in Kotlin. Here's an example of a class with instance methods and companion methods.

 class MyClass {
        companion object MyCompanionObject {
            fun actsAsStatic() {
                // do stuff
            }
        }

       fun instanceMethod() {
            // do stuff
        }
    }

Invoking the instance method would look like this.

    var myClass = MyClass()
    myClass.instanceMethod()

Invoking the companion object method would look like this.

    MyClass.actsAsStatic()

See the Kotlin docs for more info.

Kotlin Object Vs Companion Object - DEV, It was in the context of a PR where kotlin class and a bunch of functions inside So, decided to do a bit reading and document the differences, and use-cases class MyClass { // some implementations companion object { val� Coming to Kotlin, many users look for the equivalent facility out of habit and end up overusing companion objects. Kotlin completely decouples the notions of a file and a class. You can declare any number of public classes is the same file.

An object, or an object declaration, is initialized lazily, when accessed for the first time.

A companion object is initialized when the corresponding class is loaded. It brings about the 'static' essence, although Kotlin does not inherently support static members.

Kotlin Object Vs Companion Object | by Bigyan Thapa, It was in the context of a PR where kotlin class and a bunch of functions "why we can't convert the class into an object and get rid of the companion object {} ? So, decided to do a bit reading and document the differences, and use-cases for� Object Expressions and Declarations. Sometimes we need to create an object of a slight modification of some class, without explicitly declaring a new subclass for it. Kotlin handles this case with object expressions and object declarations. Object expressions. To create an object of an anonymous class that inherits from some type (or types), we

Companion object exists because you can call companion objects' functions/properties like it is a java static method/field. And for why your Holder is allowed, well, there is no reason that declaring a nested object is illegal. It may comes in handy sometimes.

Companion object in Kotlin � Suneet Agrawal, Now when we try to implement the same class in the Kotlin, the private static instance and the managerInstance property will be moved to companion object. In Java, you typically have classes that have some static content, but also some non-static / instance content. Kotlin allows you to do something similar with companion objects, which are objects tied to a class, meaning a class can access it's companion object's private functions and properties:

As Kotlin in Action states

The object keyword comes up in Kotlin in a number of cases, but they all share the same core idea: the keyword defines a class and creates an instance (in other words, an object) of that class at the same time.

when it comes to a plain object and a companion object, only significant difference is that properties and functions of a companion object can be accessed direcly by using the name of the containing class. which makes it seem like java static member access.

for example if you have following class

class Temp{
    object Holder{
        fun foo() = 1
    }

    companion object{
        fun foo() = "Hello World"
    }
}

then you can access both of these objects as following From containing class

foo()   // call to companion object function
Holder.foo() // call to plain object function

and from outside the class

Temp.foo() // call to companion object function
Temp.Holder.foo() // call to plain object function

Under the hood every object declaration creates a singleton. in case of companion object the singleton object is created in the static initializer of the containing class. but in case of plain objects singleton instance is created lazily when the object class is accessed for the first time.

You can see it for yourself by compiling the kotlin class and then decompiling the generated class files using some java decompiler.

as to why there is also the possibility of declaring a normal object in the class. consider the following class where member object is very usefull.

data class Employee(val name: String) {
    object NameComparator : Comparator<Employee> {
         override fun compare(p1: Employee, p2: Employee): Int =
             p1.name.compareTo(p2.name)
    }
}

now we can sort a list of employees as

list.sortedWith(Employee.NameComparator))

A few facts about Companion objects, Instead, you have to add a Companion object to your classes to wrap difference: the Companion is exposed as a static member in the Java� Class is a blueprint or template from which objects are created. Object is an instance of a class. Here is a simple example: class A val a = A() In above example A is a class, but a is pointing to an object. Class is what is defined using: class keyword; object declaration; object expression; companion object; All objects are

Objects in Kotlin, Learn what objects are in Kotlin and how they can make your code cleaner and a standard object definition, only with a couple of additional features to make A companion object is always declared inside of another class. In the program, Test object declaration is marked with keyword companion to create a companion object. Hence, it is possible to call callMe() method by using the name of the class as: Person.callMe()

#4.5 Android Kotlin Tutorial: Companion Object and Object , Use STATICS in Kotlin analogous to Java. For that learn to use Companion Object and Object Duration: 9:42 Posted: Jun 7, 2018 A companion object is common to all instances of the classes. It can access all members of the class too, including the private constructors. A companion object is initialized when the class is instantiated. A companion object CANNOT be declared outside the class. Let’s look at a simple example of kotlin companion object.

Kotlin-Series — Object Declaration & Companion Objects in Kotlin , An Object declaration inside a class is marked with the companion In which we will learn What is the actual difference between val and var. Objects in Kotlin add a whole extra layer that we can use, further streamlining our code and making it easier to develop. Companion objects then take this even further, allowing for cleaner code that is easier to maintain and work with. As always, code snippets can be found over on over on GitHub.

Comments
  • object for Singletons and companion object for static methods. Kotlin - Object declarations provides a good usage explanation.
  • Perfect! Thanks a lot for your explanation!
  • AFAIK there is some difference in the initialization order
  • What is difference? I would guess companion is initialized first, because it's tied to its class and afterwards the object is called?
  • Companion object is initialized from the static constructor of the containing class and plain object is initialized lazily on the first access to that object.
  • You answered What I want... "lifecycle". Thank you.
  • Thanks Mike! This should be the answer.
  • I had to use the method inside companion object as MyClass.MyCompanionObject.actsAsStatic() or MyClass.Companion.actsAsStatic() if the companion object didn't have a name. Is that a new change, or did I do something wrong? Thanks.