When building an abstract class where you want the...
# getting-started
m
When building an abstract class where you want the subclasses to provide some property, how would you decide between constructor arg versus abstract val?
a
abstract val unless there's a compelling reason not to in the specific case
👍 3
m
Thanks Adam. Any examples of such a compelling reason? Perhaps, not wanting to expose the property?
a
not wanting to expose the property, wanting to enforce specific implementation details of the property storage or getter
m
Nice word-for-word synchronicity there!
a
nah, I was just agreeing with you 🙂
not coincidence
m
So you’d pretty much never declare a (public)
val foo
inside a constructor?
Isn’t there also something regarding accessing abstract properties from within
init
block.
👌 1
a
I wouldn't say, "pretty much never," but there does need to be a good reason. Those good reasons do come up frequently. One great example of enforcing specific implementation details is when the base class wants a property to be immutable
👍 1
if the abstract class has an id field that shouldn't change after construction, for example
m
I typically think of most values I would pass into a constructor would be immutable anyway. But I understand your point. Perhaps the abstract class does not want to risk the subclass ‘magically’ returning different values for a property. This, and the
init
block issue, makes me think using constructor args would be a better default, and then use ‘compelling reasons’ to use abstract vals. Having said that, I like the flexibility of being able to do choose between putting
override val
in the constructor or body of the subclass.
a
This mostly comes from a preference for sticking with final classes and interfaces as the primary tools, abstract classes when you need an interface with some policy enforcement, and open classes almost never. Defaulting to abstract val without a good reason goes hand in hand with preferring interfaces over abstract classes more generally.
👍 1