Sobes.tech
Middle

When should you use 'lateinit' and 'by lazy' in Kotlin?

sobes.tech AI

Answer from AI

lateinit is used for non-nullable properties that will be initialized later, before the first access to them. It is used with var.

class UserActivity : AppCompatActivity() {
    lateinit var binding: ActivityUserBinding // Will be initialized in onCreate

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityUserBinding.inflate(layoutInflater)
        setContentView(binding.root)
        // Now binding can be used
    }
}

by lazy is used for non-nullable or nullable properties that are initialized upon first access to them. It is used with val.

class DataManager {
    val apiService: ApiService by lazy {
        Retrofit.Builder()
            .baseUrl("https://api.example.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(ApiService::class.java)
    }
}

Comparison:

Attribute lateinit by lazy
Usage var val
Property type Non-nullable Non-nullable or nullable
Initialization Later, manually On first access, automatically
Thread safety Not guaranteed by default (unless synchronized manually) Guaranteed by default (synchronized)
Null value Not allowed before initialization (will throw an exception) No (type determined by initializer)

Use lateinit when the property value depends on context or other factors and should be set after object creation but before use (e.g., binding a View in Android Activity).

Use by lazy for properties that are costly to create or may not be needed throughout the object's lifetime, or when initialization should be deferred until the first actual use.

When should you use 'lateinit' and 'by lazy' in… - sobes.tech