Sobes.tech
Middle

What is the difference between using the 'lateinit' keyword and delegation with 'by lazy {}' in Kotlin?

sobes.tech AI

Answer from AI

lateinit is used for deferred initialization of mutable properties (var) that cannot be nullable and will be initialized later, for example, in the activity or fragment lifecycle method. The compiler does not guarantee initialization, and accessing an uninitialized property will throw an UninitializedPropertyAccessException.

by lazy {} is used for deferred initialization of immutable properties (val). Initialization occurs upon the first access to the property, and the result is cached. It is thread-safe by default and guarantees that the initializer will be called only once.

Attribute lateinit by lazy {}
Applies to var val
Nullability Not nullable Not nullable
Initialization guarantee No (only by developer) Yes (on first access)
Thread safety Not guaranteed by default Yes (by default)
Property type Mutable Immutable

Example with lateinit:

class MyActivity : AppCompatActivity() {

    private lateinit var textView: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        textView = findViewById(R.id.my_text_view)
        textView.text = "Hello, lateinit!"
    }
}

Example with by lazy {}:

class MyViewModel : ViewModel() {

    private val apiService: ApiService by lazy { provideApiService() } // Initialized on first use

    private fun provideApiService(): ApiService {
        // Logic to create ApiService
        return ApiService()
    }

    fun fetchData() {
        // apiService is initialized here on first call to fetchData()
        apiService.getData()
    }
}
What is the difference between using the 'lateinit'… - sobes.tech