← Back to Kotlin Course | Chapter 7: Inheritance & Interfaces | Lesson 6 of 7

Sealed Classes क्या हैं

एक sealed class आपको संभावित subtypes की एक निश्चित, ज्ञात list देती है, ताकि Kotlin गारंटी दे सके कि आपने उनमें से हर एक को handle कर लिया है।
Syntax
kotlin
sealed class ClassName
class CaseA(val data: Type) : ClassName()
object CaseB : ClassName()

val result = when (value) {   // no else needed
    is CaseA -> value.data
    CaseB -> other
}

Declaring a Sealed Class

sealed class inheritance को subclasses के एक ज्ञात, बंद set तक सीमित करती है, जो compiler को compile time पर हर संभव subtype के बारे में पूरी तरह reasoning करने देता है।

उदाहरण: Declaring a Sealed Class

markup
sealed class Result
// Define a data class `Success`
data class Success(val data: String) : Result()
// Define a data class `Failure`
data class Failure(val error: String) : Result()

// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `result` (a `Result`), set to `Success("Loaded")`
    val result: Result = Success("Loaded")
    // Print `result` to the console, with a trailing newline
    println(result)
}

Exhaustive when Without else

चूंकि compiler किसी sealed class की हर subclass जानता है, उन सभी को cover करने वाला एक when expression को else branch की ज़रूरत नहीं और अब भी सुरक्षित रूप से compile होता है।

उदाहरण: Exhaustive when Without else

markup
sealed class Result
// Define a data class `Success`
data class Success(val data: String) : Result()
// Define a data class `Failure`
data class Failure(val error: String) : Result()

// Define the function `describe` taking `result` and returning a String
fun describe(result: Result): String = when (result) {
    is Success -> "Success: ${result.data}"
    is Failure -> "Failure: ${result.error}"
}

// Entry point: execution of the program starts here
fun main() {
    // Print `describe(Success("Data loaded"))` to the console, with a trailing newline
    println(describe(Success("Data loaded")))
    // Print `describe(Failure("Timeout"))` to the console, with a trailing newline
    println(describe(Failure("Timeout")))
}

Sealed Classes for Modeling States

Sealed classes छोटे, निश्चित set of states के लिए एक शानदार fit हैं जिनमें से हर एक को अलग data carry करना हो, जैसे किसी application में loading states।

उदाहरण: Sealed Classes for Modeling States

markup
sealed class LoadState
// Define the singleton object `Loading`
object Loading : LoadState()
// Define a data class `Loaded`
data class Loaded(val items: Int) : LoadState()
// Define a data class `Error`
data class Error(val message: String) : LoadState()

// Define the function `render` taking `state` and returning a String
fun render(state: LoadState): String = when (state) {
    is Loading -> "Loading..."
    is Loaded -> "Loaded ${state.items} items"
    is Error -> "Error: ${state.message}"
}

// Entry point: execution of the program starts here
fun main() {
    // Print `render(Loading)` to the console, with a trailing newline
    println(render(Loading))
    // Print `render(Loaded(10))` to the console, with a trailing newline
    println(render(Loaded(10)))
}

Sealed Classes Catch Missed Cases

अगर किसी sealed class में बाद में एक नई subclass जोड़ी जाए, तो कहीं और मौजूद कोई भी exhaustive when expression जो हर मौजूदा case handle करता था तब तक compile होना fail करेगा जब तक यह नए को भी handle न करे, missed logic को जल्दी पकड़ते हुए।

Note: अगर आपने यहां एक Triangle subclass जोड़ी होती, तो यह when तब तक compile होना fail करता जब तक एक Triangle branch न जोड़ी जाए।

उदाहरण: Sealed Classes Catch Missed Cases

markup
sealed class Shape
// Define a data class `Circle`
data class Circle(val radius: Double) : Shape()
// Define a data class `Square`
data class Square(val side: Double) : Shape()

// Define the function `area` taking `shape` and returning a Double
fun area(shape: Shape): Double = when (shape) {
    is Circle -> Math.PI * shape.radius * shape.radius
    is Square -> shape.side * shape.side
}

// Entry point: execution of the program starts here
fun main() {
    // Print "Circle area: ${area(Circle(2.0))}" to the console, with a trailing newline
    println("Circle area: ${area(Circle(2.0))}")
    // Print "Square area: ${area(Square(3.0))}" to the console, with a trailing newline
    println("Square area: ${area(Square(3.0))}")
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह भूल जाना कि किसी sealed class की subclasses को सभी एक ही module में रहना चाहिए (और, कुछ Kotlin versions से पहले, उसी file/package में), कहीं और रखने पर एक compile error का कारण बनते हुए।
  2. किसी sealed class पर when में एक अनावश्यक else branch जोड़ना, जो compiler की बाद में नई subtype जोड़े जाने पर चेतावनी देने की क्षमता छुपा देता है।
  3. किसी sealed class को किसी enum के साथ confuse करना; sealed subclasses हर एक अपना अलग data रख सकती हैं, एक साधारण enum के fixed constant set के विपरीत।
चैप्टर सारांश
  • sealed class सीमित करती है कि कौन सी classes इसे subclass कर सकती हैं, और सभी direct subclasses compile time पर compiler को ज्ञात होनी चाहिए।
  • किसी sealed class के subtypes पर एक when expression बिना else branch के exhaustive हो सकता है, क्योंकि compiler हर संभावना जानता है।
  • Sealed classes संबंधित, लेकिन structurally अलग, states या results के एक निश्चित set को represent करने के लिए आदर्श हैं।
  • बाद में एक नई subclass जोड़ने से कोई भी exhaustive when block तब तक compile होना fail करता है जब तक वह नए case को भी handle न करे।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.