https://kotlinlang.org logo
#android
Title
# android
k

knthmn

06/01/2021, 3:43 AM
I have seen people initialize variables in lifecycle classes by doing this
Copy code
class MainActivity : ComponentActivity() {
    
    val foo by lazy { Foo() }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        foo // initialize
    }
}
I see the following benefits • the "initialization" of the value is visually closer to where it is defined •
foo
is a
val
Are there any disadvantages doing this? What do you guys prefer?
K 1
opposed to
Copy code
class MainActivity : ComponentActivity() {

    lateinit var foo: Foo

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        foo = Foo()
    }
}
j

Jiddles

06/01/2021, 9:17 AM
I think if you need initialise something at particular point in the lifecycle, a lazy probably isn’t the best fit IMO because unless you explicitly make a call like you have in your example, it will be fetched when it’s referenced later (I assume). If I saw a lazy, I would assume when it’s initialised isn’t important. I feel like lateinits cause a lot of problems but I prefer your lateinit example.
👍🏼 1
2 Views