我最近读了关于const关键字的文章,我很困惑!我找不到const和val关键字之间的任何区别,我的意思是我们可以用它们来创建一个不可变变量,还有什么我遗漏的吗?


当前回答

val和const都是不可变的。

Const用于声明编译时常量,而val用于声明运行时常量。

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

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

其他回答

const是编译时常量。这意味着它们的值必须在编译时赋值,而不像val那样可以在运行时赋值。

这意味着,const永远不能被赋值给函数或任何类构造函数,而只能赋值给String或原语。

例如:

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

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

您可以将Kotlin转换为Java。 然后你可以看到const比val多一个静态修饰符。 像这样的简单代码。

科特林:

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

Java(部分):

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

const kotlin到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";

简单地说

const变量的值在编译时已知。 val的值用于在运行时定义常量。

示例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"
}

这是因为getCar()在运行时被求值并将值赋给Car。

此外,

Val是只读的意味着在运行时是不可变的 Var是在运行时已知的可变变量 Const是不可变的,并且是编译时已知的变量

再补充一下卢卡的回答:

编译时常量 在编译时已知值的属性可以使用const修饰符标记为编译时常量。这些属性需要满足以下要求: 对象声明或伴生对象的顶级或成员。 初始化为String类型或基本类型的值 没有自定义getter 这些属性可以在注释中使用。

来源:官方文件

对于那些在val和const中寻找哪个更合适或更有效的人:

对于String或任何基本数据类型,建议使用const val而不是val。因为val在运行时是已知的,所以当你的应用程序运行时,它会处理所有的值。另一方面,const val将在编译时提前执行此操作。所以const val会给出更好的结果。