Advantage of using const in Kotlin

Authors
  • Amit Shekhar
    Name
    Amit Shekhar
    Published on
Advantage of using const in Kotlin

I am Amit Shekhar, I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos.

Join my program and get high paying tech job: amitshekhar.me

Before we start, I would like to mention that, I have released a video playlist to help you crack the Android Interview: Check out Android Interview Questions and Answers.

In this blog, we are going to learn about the advantage of using const in Kotlin.

It is one of the commonly asked questions during the Android Interview.

The best way to learn this is by taking an example.

Assume that we have an object class Constants in Kotlin.

object Constants {

    val NAME = "Amit"

}

Note: We are not using const.

And, we are accessing this NAME as below:

fun testValWithoutConst() {
    val name = Constants.NAME
}

Now, we need to decompile this code. For that, we will have to convert this Kotlin source file to a Java source file.

Steps to convert from Kotlin source file to Java source file and decompile in Android Studio:

  • Tools > Kotlin > Show Kotlin Bytecode. You will get the bytecode of your Kotlin file.
  • Now click on the Decompile button to get your Java code from the bytecode.

Here, I have kept only the important lines of the code and removed other lines for brevity.

We will get the following output:

public final void testValWithoutConst() {
  String name = Constants.INSTANCE.getNAME();
}

The output is as expected.

The above example was without the const keyword. Now, let's use the const keyword.

For that, we will modify our object class Constants in Kotlin as below:

object Constants {

    const val NAME = "Amit"

}

Note: We are using const.

And, we are accessing this NAME as below:

fun testValWithConst() {
    val name = Constants.NAME
}

Now, when we decompile this code, we will get the following output:

public final void testValWithConst() {
  String name = "Amit";
}

Here, we can see that the variable NAME has been replaced by its value which is Amit.

As the value has been inlined, there will be no overhead to access that variable at runtime. And hence, it will lead to a better performance of the application.

This is the advantage of using const in Kotlin.

Watch the video format: Advantage of using const in Kotlin

Prepare yourself for Android Interview: Android Interview Questions

That's it for now.

Thanks

Amit Shekhar

You can connect with me on:

Read all of my high-quality blogs here.