我在 fragment 中被声明为 lateinit var binding: EditInsuranceDialogBinding
中的绑定(bind)对象,但一位同事说“这是一个不好的做法,Binding 对象应该是 可选。”
因此在声明中将改为这样: var binding: EditInsuranceDialogBinding? = null
,在onCreateContentView
中初始化,并在onDestroyView
中设为null
我想知道选择哪种绑定(bind)类型最好(可选或不可选)? lateinit 是否会在编译器和内存方面消耗大量资源?什么时候我们应该不选择lateinit,什么时候我们应该使用它?
最佳答案
but a colleague said "This is a bad practice and Binding object should be Optional . "
您的同事可能真正的意思是应该将绑定(bind)对象包装在Optional
中。
I want to know what is the best to choose the type of Binding (optional or not)?
lateinit var
并不是邪恶的。然而,它并不适合所有情况。
在这种情况下,绑定(bind)对象具有特定的生命周期,我们需要在onDestroyView()
之后停止使用它。如果您将该属性声明为:
private lateinit var binding: EditInsuranceDialogBinding
...那么您无法在 onDestroyView()
之后将其设置为“我们没有有效的绑定(bind)”。很容易在 onDestroyView()
之后运行的 fragment 中包含代码,并且该代码需要知道使用绑定(bind)是不安全的。无法创建表示“使用绑定(bind)不安全”状态的 EditInsuranceDialogBinding
实例。
您选择的替代方案是合理的:
private var binding: EditInsuranceDialogBinding? = null
...在 onDestroyView()
中将 binding
设置为 null
。
您还可以选择:
private var binding: Optional<EditInsuranceDialogBinding> = Optional.empty()
...您在 onDestroyView()
中将 binding
设置回 Optional.empty()
的位置。还有自定义绑定(bind)委托(delegate),例如this one ,您可以使用。
and does lateinit cost a lot in the compiler and memory ?
没有。
When we should NOT choose lateinit and when we should use it?
当我非常确信我会在使用前对其进行初始化时,我尝试仅使用lateinit
。
关于android - 我们什么时候应该为对象选择 Lateinit ?将绑定(bind)设置为非可选和延迟初始化是一种不好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67938125/