What is preferred: `lateinit var` or assigning the...
# announcements
n
What is preferred:
lateinit var
or assigning the value to a
val
that way it’s not mutable? Example lateinit var:
Copy code
late init var foo: Bar()

fun goTime() {
   foo = Bar()
   println(foo)
}
Example var:
Copy code
var foo: Bar? = null

fun goTime() {
   val foo = foo ?: Bar()
   println(foo)
}
s
Both has different usecase. I tend to use val more unless I need mutablity. The only place I would use lateinit var when I don't need mutability is when I can't provide it's initial value at the time of declaration. E.g.- field dependency injection, Android classes
🙏 1
e
not a great example as lateinit primitive doesn't work… https://youtrack.jetbrains.com/issue/KT-15284
if it must be deferred, I would use something like
Copy code
val foo: Int by lazy {
    1
}
where possible
s
For primitives, instead of lateinit, Delegates.notNull is used.
n
ahh, yeah that was just an example. I’ll update it so it’s an object.