Colton Idle
03/09/2023, 6:16 PMsealed class CallbackItemType(){
class Book(val id: Long) : CallbackItemType()
class Magazine(val id: Long) : CallbackItemType()
class Record(val id: Long, val artist: String, val enabled: Boolean) : CallbackItemType()
}
Technically speaking, I don't think an enum would even be able to have that sort of data modelled?Casey Brooks
03/09/2023, 6:30 PMsealed class CallbackItemType(){
object Book : CallbackItemType()
object Magazine : CallbackItemType()
object Record : CallbackItemType()
}Colton Idle
03/09/2023, 6:35 PMCasey Brooks
03/09/2023, 7:08 PMswitch statements, but classes are not allowed.
Java 17 introduces both sealed classes and pattern matching for switch, which gives Java switch statements similar functionality to Kotlin’s when, but a bit more flexible and more powerful. But before 17, enums were the only real way to have limited type-safe code.Francesc
03/09/2023, 7:26 PMid is common, move it to the base class, otherwise make the base class an interfaceFrancesc
03/09/2023, 7:27 PMsealed interface CallbackItemType{
val id: Long
class Book(override val id: Long) : CallbackItemType
class Magazine(override val id: Long) : CallbackItemType
class Record(override val id: Long, val artist: String, val enabled: Boolean) : CallbackItemType
}Francesc
03/09/2023, 7:28 PMCasey Brooks
03/09/2023, 7:32 PMid to the base class for this example. If there’s nothing you will do “common” with that ID, there’s no need to add that extra boilerplate. In other words, if you never need to do something like fun CallbackItemType.doAThing() { doSomethingCommonWithId(id) }, it’s unnecessary abstraction that actually makes things harder to maintain in the long-term.
Using a sealed interface instead of sealed class is a good idea though. Doesn’t really change much other than making the class slightly “lighter”, since inheritance is slightly “heavier” at runtime than implementation, but it does make the code a slight bit shorter since you can omit the parentheses on : CallbackItemType