Is it bad practice to use an abtract `val` propert...
# getting-started
j
Is it bad practice to use an abtract
val
property in an abstract class's initialization? I notice that it only works when subclasses override the getter specifically, which makes sense. But there doesn't seem to be any way to enforce that subclasses specifically override the getter rather than just initialize the property (which causes an error in the super's init).
v
Generally, I'd say yes. Superclass constructor is called before subclass properties are initialized and subclass constructor is executed. This is called "leaking this" iirc. Even if you call an overridden getter or other method, the partially initialized instance is leaked and might not behave properly. It is the same in Java or any other JVM language. There are some special cases where it might be ok. For example if you write Gradle logic and there have abstract getters for injected services or for
Property
properties. Using those in the constructor for example to set conventions usually is fine, as you know that the decorated class Gradle generates has the getters implemented in a compatible way. But even there it is most often better to not do such things in the constructor of the task or extension, not particularly because of the leaking this, but because it is more idiomatic to have tasks and extensions just as providing the work logic or configuration dsl but otherwise as opinionless as possible, and add the opinion like setting property conventions or wiring task properties and extension properties together done in the plugin that registers those tasks or extensions, which improves potential reusability.
d
Why not make that property a constructor parameter for the super class? I think that's the right pattern here.
v
Depends on situation. For the Gradle magic this does not work for example.