Init block and property setters

When we declare a var property in kotlin and dont initialize it complains.
Screen Shot 2021-01-06 at 8.16.11 AM

But we can use the init block to assign a value to it and that works.
Screen Shot 2021-01-06 at 8.16.42 AM

But now if the property has a setter, then we still have to make the assignment in place.Screen Shot 2021-01-06 at 8.18.17 AM

Why is it designed this way ?
Screen Shot 2021-01-06 at 8.20.56 AM

The setter’s body code is purposefully allowed to do whatever it wants. It could access the field before assigning it. It might never even assign the field at all. So, for example, if it accesses the field before assigning it, the field would not be initialized yet.

In the end, it probably comes down to current flow analysis not being powerful enough to guarantee the field gets initialized before access.

If you consider how this class is compiled into jvm byte code, it becomes very clear. Personally I don’t like explanations that use the jvm as an excuse, though it shows how this could be a complex problem to solve.

2 Likes