Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - what's the reasoning behind "const"

It has been already clarified what's the difference between val and const val here.

But my question is, why we should use const keyword? There is no difference from the generated Java code perspective.

This Kotlin code:

class Application

private val testVal = "example"

private const val testConst = "another example"

Generates:

public final class ApplicationKt
{
    private static final String testVal = "example";
    private static final String testConst = "another example";
}
like image 778
Marek J Avatar asked Jan 02 '23 15:01

Marek J


1 Answers

It's not always the same generated code.

If testVal and testConst were public, the generated code wouldn't be the same. testVal would be private with a public get, whereas testConst would be public, without any getter. So const avoids generating a getter.

like image 185
JavierSA Avatar answered Jan 05 '23 16:01

JavierSA