0

文档显示了用于检查是否已初始化 lateinit var 的示例:

println("isInitialized before assignment: " + this::lateinitVar.isInitialized)
lateinitVar = "value"
println("isInitialized after assignment: " + this::lateinitVar.isInitialized)

为什么它必须使用“this::”作为其限定符

4

1 回答 1

1

答案在于反编译的字节码。当您调用lateinitVar带有初始化检查的访问字段时:

println("logProperty: " + lateinitVar)

编译为:

StringBuilder var10000 = (new StringBuilder()).append("logProperty: ");
String var10001 = this.lateinitVar;
if (this.lateinitVar == null) {
   Intrinsics.throwUninitializedPropertyAccessException("lateinitVar");
}
String var1 = var10000.append(var10001).toString();
System.out.println(var1);

但是这个:

println("logProperty: " + this::lateinitVar.isInitialized)

编译为:

String var1 = "logProperty: " + (((MyClass)this).lateinitVar != null);
System.out.println(var1);
于 2019-05-15T21:34:46.920 回答