https://kotlinlang.org logo
#getting-started
Title
# getting-started
m

Mark

02/22/2021, 3:43 AM
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

Adam Powell

02/22/2021, 3:52 AM
abstract val unless there's a compelling reason not to in the specific case
👍 3
m

Mark

02/22/2021, 3:52 AM
Thanks Adam. Any examples of such a compelling reason? Perhaps, not wanting to expose the property?
a

Adam Powell

02/22/2021, 3:54 AM
not wanting to expose the property, wanting to enforce specific implementation details of the property storage or getter
m

Mark

02/22/2021, 3:56 AM
Nice word-for-word synchronicity there!
a

Adam Powell

02/22/2021, 3:56 AM
nah, I was just agreeing with you 🙂
not coincidence
m

Mark

02/22/2021, 4:02 AM
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

Adam Powell

02/22/2021, 4:13 AM
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

Mark

02/22/2021, 4:19 AM
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

Adam Powell

02/22/2021, 4:43 AM
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
3 Views