How to Lazy Initialize with a parameter in Kotlin

In Kotlin, I could do Lazy Initialization without a parameter, as follows.

val presenter by lazy { initializePresenter() } abstract fun initializePresenter(): T 

However, if I have a parameter in my initializerPresenter ie viewInterface , how can I pass this parameter to Lazy Initiallization?

 val presenter by lazy { initializePresenter(/*Error here: what should I put here?*/) } abstract fun initializePresenter(viewInterface: V): T 
+7
kotlin
source share
1 answer

You can use any element within the available scope, that is, parameters, properties and constructor functions. You can even use other lazy properties, which can sometimes be quite useful. Here are all three options in one piece of code.

 abstract class Class<V>(viewInterface: V) { private val anotherViewInterface: V by lazy { createViewInterface() } val presenter1 by lazy { initializePresenter(viewInterface) } val presenter2 by lazy { initializePresenter(anotherViewInterface) } val presenter3 by lazy { initializePresenter(createViewInterface()) } abstract fun initializePresenter(viewInterface: V): T private fun createViewInterface(): V { return /* something */ } } 

Any functions and properties of the top level may also be used.

+15
source share

All Articles