“lateinit” or “by lazy” when defining global android.widget var/val

天涯浪子 提交于 2019-12-05 03:42:57

There's one pitfall with by lazy. The widget property would be read-only and therefore technically final (in Java terms). But there's no documented guarantee that onCreate() is called only once for an instance. Also findViewById() could return null.

So using lateinit is preferable and you'll get an exception to tell you if the val was used before onCreate().

A third possibility would be Android synthetic properties. Then you don't need to worry about the variables at all.

import kotlinx.android.synthetic.main.activity_main.*

helloWorldTextView.text = "Hello?"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!