Christophe Beyls
1 min readFeb 25, 2019

--

I would like to add that overriding the fields in the subclasses is only necessary because you decided to have your subclasses declared as data classes. The main limitation of data classes is that all arguments in their primary constructor need to be property declarations.

If data class is not a requirement, you can simply declare the common fields as final in the base sealed class and you don’t need to override them in the subclasses. The subclasses can simply delegate the value passed in their constructor to the parent class:

sealed class PowerTool(val name: String, val price: Double)class CircularSaw(val diameter: Int, val cordless: Boolean, name: String, price: Double): PowerTool(name, price)class DrillPress(val rpm: Int, name: String, price: Double): PowerTool(name, price)

--

--

Christophe Beyls
Christophe Beyls

Written by Christophe Beyls

Android developer from Belgium, blogging about advanced programming topics.

Responses (1)