https://kotlinlang.org logo
Title
n

Nick

12/07/2021, 11:40 PM
Is it good practice to keep your sealed/data classes outside of the class that uses it, or is it better to keep it inside? 1️⃣
class MyViewModel : ViewModel() {
    sealed class SelectedFolder {
        object Unselected : SelectedFolder()
        data class Selected(val id: String) : SelectedFolder()
    }
}
or 2️⃣
private sealed class SelectedFolder {
    object Unselected : SelectedFolder()
    data class Selected(val id: String) : SelectedFolder()
}

class MyViewModel : ViewModel() {
2️⃣ 1
I think I prefer 1️⃣ because it is clear in that class what’s going to be used and organizes it a bit more i think?
h

Haris Khan

12/08/2021, 1:14 AM
I personally use #2 to make my classes a bit easier to follow
s

Stephan Schroeder

12/08/2021, 7:44 AM
I never used #1, used to use #2, but nowadays I don't even put the children of the sealed class within the sealed class (mainly because it makes referencing the children shorter,
is Selected
instead of
is SelectedFolder.Selected
) On the other hand, i've never wrote a private sealed class 🤔
sealed class SelectedFolder
object Unselected : SelectedFolder()
data class Selected(val id: String) : SelectedFolder()

class MyViewModel : ViewModel() {
👍 1
m

Michael de Kaste

12/08/2021, 10:37 AM
we put sealed classes as seperate files just like we would enums. But that's mostly because these sealed classes are used throughout the project or module. unlike @Stephan Schroeder, I prefer nested values for the sealed class. I like treating the sealed class as an enum. The on the fly import assist helps us in immediatly abstracting away the parent selector, just like with enums, but we can still do
SelectedFolder.
and get a list of its children as suggestions.
1