Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: why the compiler needs the `const` modifier?

Tags:

kotlin

In Kotlin there are:

  • val - readonly property
  • const val - compile-time constants

From the documentation:

Compile-Time Constants

Properties the value of which is known at compile time can be marked as compile time constants using the const modifier. Such properties need to fulfill the following requirements:

  • Top-level or member of an object
  • Initialized with a value of type String or a primitive type
  • No custom getter

Given that kotlin compiler does know to identify initialized values (such as there is no need defining the variable type in an initializer):

  • Why does the compiler needs the programmer's assistance?
  • Can't it identify "properties the value of which is known at compile time" and "add" the const modifier by itself?
like image 282
Lior Bar-On Avatar asked Aug 11 '17 06:08

Lior Bar-On


People also ask

Why do we use const Val in Kotlin?

In Kotlin, as in other programming languages, properties can be mutable (changeable) or immutable (not changeable). To declare an immutable property, we utilize the terms const and val.

What is compile time constant in Kotlin?

If the value of a read-only (immutable) property is known at the compile time. Mark it as a compile-time constant using the const modifier. Such properties must be fulfilled by the following requirements. Top-level, or member of an object declaration or a companion object.

What can const do that @JvmField Cannot?

const val can only be used at the top-level or in object s, while @JvmField can be used on any property.

What is the difference between Val var const Val?

Both "val" and "const val" are used for declaring read-only properties of a class. The variables declared as const are initialized at the runtime. val deals with the immutable property of a class, that is, only read-only variables can be declared using val. val is initialized at the runtime.


1 Answers

The const modifier seriously changes the contract of a property.

For example, if you have a regular property, you may add a special getter to it without affecting the code which uses it.

On the other hand, you would have to recompile the user code in order to remove const and add getters. In other words, you loose the advantage of having a property over a field.

like image 185
voddan Avatar answered Sep 23 '22 02:09

voddan