管理活动内的对象以避免使用空值

使用Kotlin的好处之一是它的Null安全。 但是,当我使用它编程Android应用程序时,我发现自己需要使用null。 当声明我的用户界面元素,如TextViews和按钮等我需要创建私人变量初始化到每个对象onCreate期间,但这意味着我需要明确地允许在每个引用为空。 这种打败了使用Kotlin的目的之一。 有没有更好的解决方案,在我的Android活动中创建UI对象的实例。

这就是我现在这样做的。

var messageView: TextView? = null var firstNameView: EditText? = null var lastNameView: EditText? = null var ageView: EditText? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) messageView = findViewById<TextView>(R.id.message) firstNameView = findViewById<EditText>(R.id.firstName) lastNameView = findViewById<EditText>(R.id.lastName) ageView = findViewById<EditText>(R.id.age) findViewById<Button>(R.id.showMessage).setOnClickListener(this) findViewById<Button>(R.id.update).setOnClickListener(this) } 

尝试将这些定义为lateinit ,如果能保证在读取之前提供值,就应该让它们超过需要使它们为空的需求。

 lateinit var messageView: TextView lateinit var firstNameView: EditText lateinit var lastNameView: EditText lateinit var ageView: EditText 

lateinit的文档 :

通常,声明为具有非null类型的属性必须在构造函数中初始化。 但是,这往往不方便。 例如,属性可以通过依赖注入来初始化,或者在单元测试的设置方法中进行初始化。 在这种情况下,你不能在构造函数中提供一个非null初始值设定项,但是当你引用一个类的内部属性的时候,你还是要避免使用null检查。