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