Benefits of declaring a sealed class as object
Asked Answered
U

1

7

Context

I have this sealed class and each of its children:

sealed class Section

class SearchSection : Section()
class FavoritesSection : Section()
class RecommendationsSection : Section()
class ProfileSection : Section()

But I get a warning over each class declaration:

Sealed sub-classhas no state and no overrite equals

Which suggest me to declare them as:

object ProfileSection : Section()

Question

  • What is the purpose of this?
  • What are the benefits?
  • Why I should write them as object and not a class?
Unrefined answered 21/12, 2019 at 21:59 Comment(1)
Why have you used sealed class instead of enum in the first place?Sanies
B
18

First of all let me explain what is the purpose of sealed classes. The very first sentences in the official documentation say:

Sealed classes are used for representing restricted class hierarchies, when a value can have one of the types from a limited set, but cannot have any other type. They are, in a sense, an extension of enum classes.

I'm sure you are already familiar with enums, they are this special type that enables a variable to be defined as one of predefined constants and each of these can store some additional data. And there is only one instance of every constant. By this point you might have noticed that this single instance and data keeping stuff sounds like Kotlin objects. So it turns out that this enum class:

enum class Type(val value: String) {
    A("a"),
    B("b")
}

is equivalent to this sealed class:

sealed class Type(val value: String) {
    object A : Type("a")
    object B : Type("b")
}

(in fact enum constants are objects in Kotlin).

What makes sealed classes special is that they allow you to define "constants" using classes instead of objects so they can have more than one instance and therefore store an actual state, e.g.:

sealed class ApiReponse

data class Success(val data: Data) : ApiResponse()
object Error : ApiResponse()

fun getResponse(): ApiResponse {
    ...
    return if (apiCall.isSuccessful) Success(apiCall.data) else Error
}

So finally to answer your original questions:

What is the purpose of this?

The same as enum constants. If you don't need to store a state inside your "constant" and you only need a named type with optional static data then go with an object.

What are the benefits?

Why I should write them as object and not a class?

If you don't need your "constant" to have a state, it is simply a waste of memory to create a different instance of it every time you want to use it.

Biannual answered 21/12, 2019 at 23:17 Comment(1)
Thanks for that answer, it was really helpful and explanatory.Unrefined

© 2022 - 2024 — McMap. All rights reserved.