I have code in Swift.
enum QuestionnaireViewMode {
case add(input: Add)
case edit(input: Edit)
enum Add {
case building(input: BuildingInput)
case car(input: CarInput)
case park
struct BuildingInput {
let address: String
let placeName: String
}
struct CarInput {
let name: String
}
}
enum Edit {
case profile(input: ProfileInput)
struct ProfileInput {
let name: String
}
}
}
This is enum class which very easy to use, for example i can create different type of object just like this: .add(input: .car(input: .init(name: "bmw")))
. But for me not clear enum classes in kotlin, i found some similar - sealed class
and i tryed converted to:
sealed class QuestionnaireViewMode {
sealed class add(input: Add)
sealed class edit(input: Edit)
sealed class Add {
sealed class building(input: BuildingInput)
sealed class car(input: CarInput)
sealed class park
data class BuildingInput(val address: String, val placeName: String)
data class CarInput(val name: String)
}
sealed class Edit {
sealed class profile(input: ProfileInput)
data class ProfileInput(val name: String)
}
}
is this correct?
CodePudding user response:
Your sealed classes need to extend their parent. And you are using sealed class
instead of fun
for your builder functions, which doesn’t make sense. But since these are classes you don’t need that because you can call the constructors directly. Also, since you have no commonly shared state, these can be sealed interfaces instead of sealed classes, which is a little simpler because you don’t have to worry about constructors.
Here is how I would design it:
sealed interface QuestionnaireViewMode {
sealed interface Add: QuestionaireViewMode {
data class BuildingInput(val address: String, val placeName: String): Add
data class CarInput(val name: String): Add
}
sealed interface Edit: QuestionaireViewMode {
data class ProfileInput(val name: String): Edit
}
}
Usage:
val myInput: QuestionaireViewMode =
QuestionaireViewMode.Add.CarInput(“bmw”)