在kotlin中作一次Lateinit,为什么必须使用“ this ::”

时间:2019-03-13 14:46:51

标签: kotlin-lateinit

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

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

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

1 个答案:

答案 0 :(得分: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);