Member-only story

Sealed Class in Kotlin — What, When, Where, Why and How?🚀

Sealed class provides a restricted hierarchy, which helps you write better type safety and exhaustive when statements.
Let us understand step by step what is sealed class is, when should it be used, where is it useful, and how is it written!

sealed class vs sealed interface

💡 What is Sealed Class?

🔹A sealed class is a special type of abstract class that allows a limited set of subclasses.
🔹This means that you can only inherit this class from within this file, not the second one.
🔹It is more flexible than an enum class because only values ​​can be defined in an enum, but multiple types and properties can be kept in a sealed class.

⏳ When to use Sealed Class?

🔹When a fixed hierarchy is required, like API response handling or state management.
🔹When exhaustive checking is required in an whenexpression.
🔹More flexibility than enum class is required.

Example:

sealed class ApiResponse {
data class Success(val data: String) : ApiResponse()
data class Error(val message: String) : ApiResponse()
object Loading : ApiResponse()
}

fun handleResponse(response: ApiResponse) {…

--

--

No responses yet