Difference between lazy{} vs getter() initialization in kotlin
Asked Answered
S

1

10

In kotlin we can use both of these approach lazy{} and getter()

lazy initializaiton:

internal val connector by lazy {
        serviceConnector
    }

getter():

internal val connector : ServiceConnector
        get() = serviceConnector

When to use which approach and what actually does these two approach under the hood. Which one is best approach?

Smoke answered 17/3, 2019 at 19:19 Comment(0)
E
10

When you use the lazy delegate, the val is initialized only when you use it the first time. So, in your code, the first time you access connector, the code inside the lambda is run, and the result is assigned to the val.

get(), instead, is used to redefine what happens when you try to access the val.

Excessive answered 17/3, 2019 at 19:29 Comment(3)
If, I am changing the serviceconnector?Smoke
I edited my answer, because the second part was wrong. When you change serviceConnector, you are also changing what is returned by get(), since each time you access connector you run the code in get(). With lazy instead, the val is assigned at the time of first usage, then doesn't change anymore.Excessive
Can we use lazy and get at the same time, I couldn't figure out how to use get to modify the behaviour of getter calls with by lazy on the same variable, ThanksObstinacy

© 2022 - 2024 — McMap. All rights reserved.