DEV Community

Cover image for Advantage of using const in Kotlin
Amit Shekhar
Amit Shekhar

Posted on • Edited on • Originally published at outcomeschool.com

Advantage of using const in Kotlin

Hi, I am Amit Shekhar, Co-Founder @ Outcome School • IIT 2010-14 • 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.

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.

This article was originally published at Outcome School.

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

Assume that we have a class MyClass in Kotlin.

class MyClass {

    companion object {
        const val FILE_EXTENSION = ".png"
        val fileName:String
            get() = "Img_" + System.currentTimeMillis() + FILE_EXTENSION
    }

}
Enter fullscreen mode Exit fullscreen mode

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.

We will get the following:

public final String getFileName() {
   return "Img_" + System.currentTimeMillis() + ".png";
}
Enter fullscreen mode Exit fullscreen mode

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

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

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.

That's it for now.

Thanks

Amit Shekhar

Co-Founder @ Outcome School

You can connect with me on:

Read all of our blogs here.

Top comments (0)