ELEVATE YOUR BUSINESS WITH

Limitless customization options & Elementor compatibility let anyone create a beautiful website with Valiance.

Sealed Class in Kotlin

SELECT * FROM `itio_tutorial_master` WHERE `tutorial_menu`='25' AND `tutorial_submenu`='98' AND `tutorial_status`=1 LIMIT 1

Sealed Class in Kotlin

📌 Sealed Class in Kotlin

A Sealed Class in Kotlin is a special type of class that is used to represent a restricted hierarchy of classes. It ensures that all subclasses are known and defined within the same file, providing better control over data modeling.

Sealed classes are often used when you have a fixed set of types that a variable can be, similar to Enums but more flexible.


✅ Key Features of Sealed Classes

  • Restricted Inheritance → All subclasses must be defined in the same file.

  • Improved Safety → Ensures exhaustive when statements, eliminating the need for else.

  • Data Modeling → Great for representing state or result types.

  • Abstract by Default → Cannot be directly instantiated.


✅ Syntax of Sealed Class

kotlin

sealedclassResult { dataclassSuccess(valdata: String) : Result() dataclassError(val message: String) : Result() object Loading : Result()}

  • sealed class Result → A sealed class called Result.

  • data class → Represents different outcomes (Success, Error).

  • object → Represents a singleton (Loading).


✅ Using Sealed Classes with When

Sealed classes are commonly used with when expressions for type-checking.

📌 Example:

kotlin

fun(result: Result) { (result) { is Result.Success -> println("Success: ${result.data}") Result.Error -> println("Error: ${result.message}") Result.Loading -> println() }}

  • No else required → The when statement is exhaustive because all subclasses are covered.


✅ Why Use Sealed Classes?

  • State Management: Useful in state-driven applications like mobile apps.

  • Error Handling: Ideal for representing API responses (Success, Error, Loading).

  • Clean Code: Reduces the need for complex conditional statements.


✅ Comparison: Sealed Class vs Enum

FeatureSealed ClassEnum Class
FlexibilityCan have multiple properties and methodsLimited to constant values only
SubclassingSupports data classes and objectsDoes not support subclassing
Data ModelingGood for complex state managementSuitable for simple state management
When ExhaustivenessEnsures exhaustive when statementsRequires else statement sometimes


✅ Conclusion

  • Use Sealed Classes when you have a finite set of subclasses representing various states.

  • It improves safety by ensuring all cases are handled.

  • Combine sealed classes with when statements for clean and maintainable code.

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql