androidandroid-studiokotlinkotlin-lateinit

I have a code where a lateinit variable was initialized after it was called and I don't know how


While I was following up with the Developing Android Apps with Kotlin course on udacity I found that the instructor has made a lateinit variable lateinit var diceImage: ImageView as she will initialize it later before it's called
*The lateinit variable was called in the rollDice() function but the variable was initialized after the function was called in the setOnClickListner

rollButton.setOnClickListener {
            rollDice()
        }
        diceImage = findViewById(R.id.dice_Image)

You can find the full code below

 package com.example.diceroller

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import kotlin.random.Random

class MainActivity : AppCompatActivity() {
    private var rollNumber:Int = 0
    lateinit var diceImage: ImageView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val rollButton: Button = findViewById(R.id.roll_Button)
        rollButton.setOnClickListener {
            rollDice()
        }
        diceImage = findViewById(R.id.dice_Image)
    }
    fun rollDice() {
        val diceImage: ImageView = findViewById(R.id.dice_Image)
        var randomInt: Int
        do {
           randomInt = Random.nextInt(6) + 1
        } while (randomInt == rollNumber)
        rollNumber = randomInt
        when (rollNumber) {
            1 -> diceImage.setImageResource(R.drawable.dice_1)
            2 -> diceImage.setImageResource(R.drawable.dice_2)
            3 -> diceImage.setImageResource(R.drawable.dice_3)
            4 -> diceImage.setImageResource(R.drawable.dice_4)
            5 -> diceImage.setImageResource(R.drawable.dice_5)
            else -> diceImage.setImageResource(R.drawable.dice_6)
        }
    }
}

Since I am new to android development I don't How did she initialize it after calling it in the roleDice() function

Can anyone clear this out for me? .... Shouldn't it be called before the setOnClickListner?

Thanks for helping!


Solution

  • setOnClickListener just registers a callback lambda that will be invoked whenever the rollButton is clicked, calling setOnClickListener does not immediately invoke rollDice(). The onCreate() method gets called very early in the AppCompatActivity's lifecycle, so your users won't be able to tap the button before the diceImage = findViewById(R.id.dice_Image) line runs, hence this is code is perfectly safe.