Kotlin Enum Recipes
arturdryomov.online/posts/kotlin-enum-recipes/Posted Oct 8, 2019, 8:11 PM UTC
Posted Oct 8, 2019, 8:11 PM UTC
Use CamelCase, don’t be ashamed. I doubt that anyone names sealed class using the UPPERCASE notation.
Do not compare an enum to a sealed class. Sealed classes can have as many instances as you want whereas enums represent a limited set of instances.
That's why you check for the type when using sealed classes and for identity when using enums.
// type check using sealed class
instance is MySealedClass
// equality or identity check using enum
instance === MyEnum.MY_INSTANCE
The official Kotlin documentation names enum entries with UPPERCASE. I suggest sticking to that.
There is catch though - a class can have a single companion object
That might be true, but a class can have multiple named objects:
class MyClass {
// namespace MyObject
companion object {
val className = "MyClass"
}
// namespace MyObject.Numbers
object Numbers {
val one = 1
val two = 2
}
// namespace MyObject.Chars
object Chars {
val a = 'a'
val b = 'b'
}
}
Wow, I didn’t believe so much can be said about enums.
enum class IsTrue {
Yes,
No
}
get those pesky booleans out of your life
Good information
On a minor note, I'd refactor your example with sections to make use of ranges instead of your own implementation of it, such that
enum class Section(@StringRes val title: Int, val from: Int, val to: Int) {
Dozen(R.string.Section_Dozen, from = 0, to = 10),
Dozens(R.string.Section_Dozens, from = 11, to = Int.MAX_VALUE),
}
listOf(1, 2, 3, 42).groupBy { number ->
Section.values().find { it.from <= number && number <= it.to }
}
becomes
enum class Section(@StringRes val title: Int, val range: IntRange) {
Dozen(R.string.Section_Dozen, 0..10),
Dozens(R.string.Section_Dozens, 11..Int.MAX_VALUE),
}
listOf(1, 2, 3, 42).groupBy { number ->
Section.values().find { it.range.contains(number) }
}
[deleted]
His argument doesn't even really hold water because he seems to be operating under a misunderstanding. He says no one would name sealed classes like that, which, sure, but they're classes, not constants. He then shows code with a few constants, in which he used the SCREAMING_SNAKE_CASE style for the constants, so he seems to be an advocate of doing that style for constants, but not enum constants. That just creates a very inconsistent style, and quite frankly, looks ugly.