lateinit var 和var 区别

如果说 lateinit var 和普通的var 有什么区别的话,可以看这篇文章
定义了 aa 是 lateinit String ,而 bb 是 String?。

class Test {

    lateinit var aa: String
    var bb: String? = null
}

通过 as 的 kotlin 编译 tools -- kotlin -- show kotlin bytecode 里面的 decompile

public final class Test {
   @NotNull
   public String aa;
   @Nullable
   private String bb;

   @NotNull
   public final String getAa() {
      String var10000 = this.aa;
      if (this.aa == null) {
         Intrinsics.throwUninitializedPropertyAccessException("aa");
      }

      return var10000;
   }

   public final void setAa(@NotNull String var1) {
      Intrinsics.checkParameterIsNotNull(var1, "<set-?>");
      this.aa = var1;
   }

   @Nullable
   public final String getBb() {
      return this.bb;
   }

   public final void setBb(@Nullable String var1) {
      this.bb = var1;
   }
}

可以从 java 代码看出,声明时两者都是String ,不过一个被@NotNull 一个被@Nullable 标注
,而生成的getAa方法 ,判断了a是否为空,如果aa是空的话 会抛出throwUninitializedPropertyAccessException 的异常。而 setAa方法 会判断 传入的字符串不为空,否则抛出参数为空的异常。throwParameterIsNullException,所以不允许声明latetinit 的变量不初始化赋值就进行操作。

扩展方法

class Test {
fun Int.Apple(apple:String){
      Log.i("apple",apple)
}

    fun a(){
        var b=0
        b.Apple("a")
    }
}
public final class Test {
   public final void Apple(int $receiver, @NotNull String apple) {
      Intrinsics.checkParameterIsNotNull(apple, "apple");
      Log.i("apple", apple);
   }

   public final void a() {
      int b = 0;
      this.Apple(b, "a");
   }
}

同理扩展方法就是在当前类创建一个方法,把扩展对象作为参数传入扩展方法。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容