Kotlin构造函数加不加var或者val的区别

class Greeter(name: String) {
    init {
        println("Hello, ${name}");
    }

    fun greet() {
        //println("Hello, ${name}"); name是无法访问的
    }
}

class Greeter1(val name1: String) {
    fun greet() {
        println("Hello, ${name1}");
    }
}

Greeter类的greet()方法是不能访问name的。因为没有加val或者var,就相当于Greeter类是没有name这个属性的,只是它的构造函数有个name参数而已。下面是反编译后的java代码

public final class Greeter1 {
   @NotNull
   private final String name1;

   public final void greet() {
      String var1 = "Hello, " + this.name1;
      System.out.println(var1);
   }

   @NotNull
   public final String getName1() {
      return this.name1;
   }

   public Greeter1(@NotNull String name1) {
      Intrinsics.checkParameterIsNotNull(name1, "name1");
      super();
      this.name1 = name1;
   }
}
// Greeter.java
public final class Greeter {
   public final void greet() {
   }

   public Greeter(@NotNull String name) {
      Intrinsics.checkParameterIsNotNull(name, "name");
      super();
      String var2 = "Hello, " + name;
      System.out.println(var2);
   }
}

你可能感兴趣的:(Kotlin构造函数加不加var或者val的区别)