What is the difference between “const” and “val”?

2019-01-21 04:08发布

问题:

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

回答1:

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


回答2:

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
  • Initialized with a value of type String or a primitive type
  • No custom getter

Such properties can be used in annotations.

Source: Official documentation



回答3:

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