Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: Difference between constant in companion object and top level

Tags:

kotlin

People also ask

What is the difference between companion object and object in Kotlin?

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. Show activity on this post.

Where do I put my constants in Kotlin?

You don't need a class, an object or a companion object for declaring constants in Kotlin. You can just declare a file holding all the constants (for example Constants. kt or you can also put them inside any existing Kotlin file) and directly declare the constants inside the file.

How do you define a constant in Kotlin?

To define a String constant in Kotlin, use constant and val keyword for the String. The following is a simple code snippet to define a String as constant which can be accessed using the name GREETING . const val GREETING = "Hello World!"

Is companion object static in Kotlin?

companion object is how you define static variables/methods in Kotlin. You are not supposed to create a new instance of Retrofit / ApiService each time you execute a request, however.


In Java you're forced to put all static field and method declarations in a class and often you even have to create a class just for that purpose. 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. You can also declare private top-level functions and variables and they'll be accessible only to the classes within the same file. This is a great way to organize closely associated code and data.

Compared to top-level declarations, the syntax of companion objects is quite unwieldy. You should use them only when you specifically want to associate some public static code or data with a class and want your users to qualify access to it with the class's name. The use cases for this are quite rare and in most cases the top-level declarations are more natural.

Whenever you have some private static code/data that you want to couple to a class, you'll be better served with private top-level declarations.

Finally, sometimes the concern of the generated bytecode matters. If, for whatever reason, you have to produce a Java class with Kotlin code such that the class has a static member, you must resort to a companion object and a special annotation.


Differences in usage

Defining the field in a companion object limits the scope it is available in without importing to only that class, which can help keeping the data from being used in unexpected places.

Defining in the file makes the field available to any code in the same package as the field.

Differences in Bytecode

const val CONSTANT = "something"

class Example {
}

Creates the following:

Example.java

public final class Example {}

XKt.java

import kotlin.Metadata;
import org.jetbrains.annotations.NotNull;


public final class XKt {
   public static final String CONSTANT = "something";
}

Whereas:

class Example {
    companion object {
        const val CONSTANT = "something"
    }
}

Creates the following:

public final class Example {
    public static final String CONSTANT = "something";
    public static final Example.Companion Companion = new Example.Companion((DefaultConstructorMarker) null);

    public static final class Companion {
        private Companion() {}

        public Companion(DefaultConstructorMarker $constructor_marker) {
            this();
        }
    }
}

I think that basically depends on whether you want that constant to be part of a class. If you put it inside a companion object, it will be accessed like this:

Example.CONSTANT

If you choose to put a constant on file level, it will be imported from other files and accessed with simply CONSTANT normally.

There are reasons for putting constants in classes as well as for putting them top-level.

Note that the const keyword can only be applied to variables of type String or primitive types (Int etc.) (reference). For most cases though, there's no need to apply the keyword. Defining constant values as shown in the following works as well:

val constantFIS = FileInputStream("path")