Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Lazy Initialize with a parameter in Kotlin

Tags:

kotlin

In Kotlin, I could perform Lazy Initialization without Parameter as below declaration.

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

However, if I have a parameter in my initializerPresenter i.e. viewInterface, how could I pass the parameter into the Lazy Initiallization?

val presenter by lazy { initializePresenter(/*Error here: what should I put here?*/) } abstract fun initializePresenter(viewInterface: V): T 
like image 853
Elye Avatar asked Mar 26 '16 05:03

Elye


People also ask

How do you do lazy initialization of variables in Kotlin?

We can pass the LazyThreadSafetyMode as an argument to the lazy function. The default publication mode is SYNCHRONIZED, meaning that only a single thread can initialize the given object. We can pass a PUBLICATION as a mode – which will cause that every thread can initialize given property.

Can we use lazy with VAR in Kotlin?

Lazy can be used only with non-NULLable variables. Variable can only be val. "var" is not allowed .

How do you initialize a lazy?

Implementing a Lazy-Initialized Property To implement a public property by using lazy initialization, define the backing field of the property as a Lazy<T>, and return the Value property from the get accessor of the property. The Value property is read-only; therefore, the property that exposes it has no set accessor.


1 Answers

You can use any element within the accessible scope, that is constructor parameters, properties, and functions. You can even use other lazy properties, which can be quite useful sometimes. Here are all three variant in a single 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 */   } } 

And any top-level functions and properties can be used as well.

like image 104
Michael Avatar answered Sep 28 '22 07:09

Michael