Jérôme Gully
01/14/2020, 2:50 PMopen class ParticipantsExtension {
companion object {
const val ELEMENT = "participants"
}
open fun getElement() = ELEMENT
fun parse() {
// common code used with ELEMENT from child
}
}
class UpdatedParticipantsExtension : ParticipantsExtension() {
companion object {
const val ELEMENT = "updated-participants"
}
override fun getElement() = ELEMENT
}
class AddedParticipantsExtension : ParticipantsExtension() {
companion object {
const val ELEMENT = "added-participants"
}
override fun getElement() = ELEMENT
}
IS there a better way with no redundant code ?
I must access overridden ELEMENT
as static fiel in an other class, AND use ELEMENT
in the base function parse()
with the overridden valueGiorgos Neokleous
01/14/2020, 3:14 PMgetElement()
value or is it just for conditional logic? If it's only for conditional logic, you could replace the above with Sealed Classes and have an exhaustive when
statement to handle all casesMike
01/14/2020, 3:22 PMsealed class
as the correct approach here.Jérôme Gully
01/14/2020, 3:36 PMgetElement()
is for use inside the parent method parse()
. So i guess sealed class with a property in the parent class and overirded in each child class constructor is the best choice ?Matteo Mirk
01/14/2020, 3:57 PMgetElement()
and just use the property.
About using sealed classes, consider if this hierarchy has to be closed only for you to control, or can be extended by users of your code — if it’s a library. Using sealed
cuts off the latter possibility,jimn
01/17/2020, 1:05 PMMike
01/17/2020, 1:22 PMjimn
01/17/2020, 2:04 PM