xiimoss
xiimoss

Reputation: 805

Managing Objects within Activities to avoid using Null

One of the benefits of using Kotlin is its Null safety. However when I have been programming Android Apps using it, I have found myself needing to use null. When declaring my UI elements such as TextViews and Buttons etc. I need to create private variables that are initialised to each object during the onCreate, but this means i need to explicitly allow null on each reference. This kind of defeats one of the purposes of using Kotlin. Is there a better solution, to creating instances of UI Objects within my activities in Android.

This is how I am doing it, at this moment.

    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)
    }

Upvotes: 2

Views: 53

Answers (1)

Todd
Todd

Reputation: 31710

Try defining these as lateinit, it should get you past the need to have them nullable if you can guarantee that you'll provide values before they are read.

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

From the documentation for lateinit:

Normally, properties declared as having a non-null type must be initialized in the constructor. However, fairly often this is not convenient. For example, properties can be initialized through dependency injection, or in the setup method of a unit test. In this case, you cannot supply a non-null initializer in the constructor, but you still want to avoid null checks when referencing the property inside the body of a class.

Upvotes: 3

Related Questions