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

前端 未结 7 2104
既然无缘
既然无缘 2020-12-22 17:20

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

7条回答
  •  南方客
    南方客 (楼主)
    2020-12-22 18:15

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

提交回复
热议问题