nullable constructor params can be assigned at ini...
# stdlib
h
nullable constructor params can be assigned at initialization to non-nullable lateinit properties. If they are null, then the property remains uninitialized, otherwise it is set.
Copy code
class Foo(bar: Int?, baz: Int?, boz: Int?) {
    lateinit var bar: Int = bar // acceptable
    lateinit var baz = baz // implicitly assigned as non-nullable
    lateinit var boz: Int? = baz // unacceptable
}
In general, I just always look for ways to avoid using
init
block, because I always think it looks really out of place, but as it is currently, afaik, the above logic is only accomplished like this:
Copy code
class Foo(bar: Int?) {
    lateinit var bar: Int

    init {
        if (bar != null) this.bar = bar
    }
}
p
At first glance this design looks strange. Maybe it is better to make property
bar
nullable? 🙂
h
it is strange, but it cropped up for me because I was writing an implementation of an interface, and didn't want to make the interface's property nullable
p
I would use
lateinit
only in cases when I am sure that variable will be initialized before usage. How would you work with your variable? You cannot be sure that it will be initialized so would you check
isInitialized
?
h
I'm comfortable with it throwing if it isn't initialized at this stage in development
p
Then you can write something like:
Copy code
class Foo(
    private val _foo: Int?
) {
    val foo get() = _foo!!
}
h
yeah, either way is just ugly :S
🤷‍♂️ 1
you'd also have to make
_foo
a var, and give it a setter to have the functionality of a lateinit var
i imagine that is exactly how lateinit is implemented under the surface