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

Colton Idle

11/30/2021, 7:20 PM
Not super comfortable with sealed classes. I'm trying to model an action type that can model things like a phone button click, or a url click, or unhandled (unknown). How does this look?
Copy code
sealed class GenericActionType {
    class Dialer(phoneUri: String) : GenericActionType()
    class Browser(url: String) : GenericActionType()
    object Unknown : GenericActionType()
}
j

Joffrey

11/30/2021, 7:25 PM
The structure looks good to me, although I would probably use
data class
for the ones with data, it's often useful for printing/copying/equaling etc. Regarding naming, maybe avoid "generic" and "type" in the name: • "generic" is not advisable because nested child classes will look weird when referenced (they use the parent type):
GenericActionType.Dialer(...)
• "Type" doesn't seem appropriate here because this is already a type, and that type represents an action, not an action type. If it were an action type you wouldn't have data associated with it like those urls Maybe
Action.Dial
would look better
c

Colton Idle

11/30/2021, 7:56 PM
True. I guess I'm trying to not interfere with other classes called Action. Great feedback though. Thanks
j

Joffrey

11/30/2021, 8:15 PM
Yeah I guess to avoid conflicts you might want to find a more precise name than
Action
but these "generic" and "type" words didn't give more precision IMO. Maybe some words from the domain would help, like
UserAction
or something
3
l

Luke

11/30/2021, 8:39 PM
Also, tiny improvement, unless
GenericActionType
defines something for the subclasses, consider using
sealed interface
c

Colton Idle

11/30/2021, 8:52 PM
ooh. good point too @Luke
a

Adam Powell

11/30/2021, 9:01 PM
you kind of have to make at least one really good mess with sealed classes and way over-modeling a domain to get a feel for when they're the right tool 🙂
(says someone who spent part of last weekend ripping out and replacing one such hierarchy from a hobby app)
😅 2
j

Jason5lee

12/01/2021, 7:36 AM
If you know about design patterns, this is what visitor pattern tries to do in a awkward way.
2 Views