What is the difference between "const" and "val"?

ConstantsKotlin

Constants Problem Overview


I have recently read about the const keyword, and I'm so confused! I can't find any difference between const and the val keyword, I mean we can use both of them to make an immutable variable, is there anything else that I'm missing?

Constants Solutions


Solution 1 - Constants

consts are compile time constants. Meaning that their value has to be assigned during compile time, unlike vals, where it can be done at runtime.

This means, that consts can never be assigned to a function or any class constructor, but only to a String or primitive.

For example:

const val foo = complexFunctionCall()   //Not okay
val fooVal = complexFunctionCall()  //Okay

const val bar = "Hello world"           //Also okay

Solution 2 - Constants

Just to add to Luka's answer:

> 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 declaration or a companion object. > - Initialized with a value of type String or a primitive type > - No custom getter > > Such properties can be used in annotations.

Source: Official documentation

Solution 3 - Constants

You can transform the Kotlin to Java. Then you can see const has one more static modifier than val. The simple code like this.

Kotlin:

const val str = "hello"
class SimplePerson(val name: String, var age: Int)

To Java(Portion):

@NotNull
public static final String str = "hello";

public final class SimplePerson {
   @NotNull
   private final String name;
   private int age;

   @NotNull
   public final String getName() {
      return this.name;
   }

   public final int getAge() {
      return this.age;
   }

   public final void setAge(int var1) {
      this.age = var1;
   }

   public SimplePerson(@NotNull String name, int age) {
      Intrinsics.checkParameterIsNotNull(name, "name");
      super();
      this.name = name;
      this.age = age;
   }
}

Solution 4 - Constants

const kotlin to Java

const val Car_1 = "BUGATTI" // final static String Car_1 = "BUGATTI";

val kotlin to Java

val Car_1 = "BUGATTI"   // final String Car_1 = "BUGATTI";

In simple Language

  1. The value of the const variable is known at compile time.
  2. The value of val is used to define constants at run time.

Example 1-

const val Car_1 = "BUGATTI"val Car_2 = getCar() ✔    
const val Car_3 = getCar() ❌ 

//Because the function will not get executed at the compile time so it will through error
 
fun getCar(): String {
    return "BUGATTI"
}

This is because getCar() is evaluated at run time and assigns the value to Car.

Additionally -

  1. val is read-only means immutable that is known at run-time

  2. var is mutable that is known at run-time

  3. const are immutable and variables that are known at compile-time

Solution 5 - Constants

Both val and const are immutable.

const is used to declare compile-time constants, whereas val for run-time constants.

const val VENDOR_NAME = "Kifayat Pashteen"  // Assignment done at compile-time

val PICon = getIP()  // Assignment done at run-time

Solution 6 - Constants

val

Kotlin val keyword is for read-only properties in comparison with Kotlin var keyword. The other name for read-only property is immutable.

Kotlin code:

val variation: Long = 100L

Java equivalent looks like this:

final Long variation = 100L;



const val

We use const keyword for immutable properties too. const is used for properties that are known at compile-time. That's the difference. Take into consideration that const property must be declared globally.

Kotlin code (in playground):

const val WEBSITE_NAME: String = "Google"

fun main() {	
    println(WEBSITE_NAME)
}

Java code (in playground):

class Playground {

    final static String WEBSITE_NAME = "Google";

    public static void main(String[ ] args) {
        System.out.println(WEBSITE_NAME);
    }
}

Solution 7 - Constants

For those who are looking which is more appropriate or efficient between val and const:

If we are going to create String or any primitive data type then we must use const val instead of val. Because val will be known at runtime, so when your app is running then it will process all the values. On other hand const val will do this earlier at compile time. So performance wise const val will give better result.

Solution 8 - Constants

Because I read a lot, that "val" means immutable: This is definitely not the case, just see this example:

class Test {
    var x: Int = 2
    val y
        get() = x
}

fun main(args: Array<String>) {
    val test = Test()
    println("test.y = ${test.y}") // prints 2
    test.x = 4
    println("test.y = ${test.y}") // prints 4
}

Sadly, true immutability you can currently only expect with const - but this only at compile time. At runtime you can't create true immutability.

val just means "readonly", you can't change this variable directly, only indirect like I have shown in the example above.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMathew HanyView Question on Stackoverflow
Solution 1 - ConstantsLuka JacobowitzView Answer on Stackoverflow
Solution 2 - ConstantsEPadronUView Answer on Stackoverflow
Solution 3 - ConstantsJin WangView Answer on Stackoverflow
Solution 4 - ConstantsShivam TripathiView Answer on Stackoverflow
Solution 5 - ConstantsKifayat UllahView Answer on Stackoverflow
Solution 6 - ConstantsAndy JazzView Answer on Stackoverflow
Solution 7 - ConstantsRahul SharmaView Answer on Stackoverflow
Solution 8 - Constantshenry86View Answer on Stackoverflow