The lazy is a very handy feature in Kotlin. We don't initialize any object unless we require it. This is quite an optimized approach. A typical case can be binding on a view with an object when required. We initialized our API client lazily:
private val retrofit: Retrofit by lazy { Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .baseUrl(baseURL) .build() }
A lazy delegated property can only be used with val. Whatever you define inside the block will get executed only once.
Use it carefully, initializing a heavy object when it is required can affect the application's response time. Do not execute functions that are doing too much inside the ...