Android Kotlin / The lateinit keyword

 通常,一个变量在被用到之前不需要初始化,而占用内存。

lateinit var diceImage : ImageView

The lateinit keyword promises the Kotlin compiler that the variable will be initialized before the code calls any operations on it.

用了 lateinit 关键字,可以保证变量不用先初始化,但在用到它的时候会初始化。

用 lateinit 的方法可以代替下面这个方法: 

//  不太好的示范
var diceImage : ImageView? = null

Therefore we don't need to initialize the variable to null here, and we can treat it as a non-nullable variable when we use it.

相比用先初始化一个空值的方法,用lateinit不用担心空值的问题。

It is a best practice to use lateinit with fields that hold views in just this way.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值