问题描述
定义全局 android.widget
变量时,例如TextView
,使用lateinit
还是by lazy
更可取?我最初认为使用 by lazy
会更受欢迎,因为它是不可变的,但我不完全确定.
When defining a global android.widget
variable, e.g. TextView
, is it preferable to use lateinit
or by lazy
? I initially thought using by lazy
would be preferred as its immutable but I'm not entirely sure.
by lazy
例子:
class MainActivity: AppCompatActivity() {
val helloWorldTextView by lazy { findViewById(R.id.helloWorldTextView) as TextView }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
updateTextView(helloWorldTextView)
}
fun updateTextView(tv: TextView?) {
tv?.setText("Hello?")
}
}
lateinit
示例:
class MainActivity: AppCompatActivity() {
lateinit var helloWorldTextView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
helloWorldTextView = findViewById(R.id.helloWorldTextView) as TextView
updateTextView(helloWorldTextView)
}
fun updateTextView(tv: TextView?) {
tv?.setText("Hello?")
}
}
在定义全局 android.widget
var/val 时,使用一个比另一个有什么好处吗?使用 by lazy
定义 android.widget
val 有什么陷阱吗?决定是否仅基于您想要可变值还是不可变值?
Are there any benefits of using one over the other when defining a global android.widget
var/val? Are there any pitfalls with using by lazy
to define a android.widget
val? Is the decision just based on whether you want a mutable or immutable value?
推荐答案
by lazy
有一个陷阱.小部件属性将是只读的,因此技术上是最终的(在 Java 术语中).但是没有文件保证 onCreate()
只为一个实例调用一次.findViewById()
也可以返回 null
.
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
.
所以最好使用 lateinit
,你会得到一个异常,告诉你 val
是否在 onCreate()
之前使用.
So using lateinit
is preferable and you'll get an exception to tell you if the val
was used before onCreate()
.
第三种可能性是 Android 综合属性.那么你根本不需要担心变量.
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?"
这篇关于“迟到"或“懒惰"定义全局 android.widget var/val 时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!