Amit Shekhar
Amit Shekhar

Amit Shekhar

Advantage of using const in Kotlin

Advantage of using const in Kotlin

Amit Shekhar's photo
Amit Shekhar
·Sep 22, 2022·

2 min read

I am Amit Shekhar, a mentor helping developers in getting high-paying tech jobs.

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 amitshekhar.me.

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
    }

}

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";
}

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

You can connect with me on:

 
Share this