← Back to Scala Course | Chapter 8: Inheritance & Traits | Lesson 7 of 7

Sealed Classes क्या हैं

एक sealed class या trait की children की एक निश्चित list होती है जो सभी एक ही file में रहनी चाहिए। यह एक बंद guest list जैसा है, ताकि Scala जांच सके कि आपने हर guest को handle किया।

In this page:

  1. Sealed Classes
Syntax
scala
sealed trait TraitName
case class First(field: Type) extends TraitName
case class Second(field: Type) extends TraitName
case object Third extends TraitName

Sealed Classes

किसी class या trait को sealed चिह्नित करना उसके सभी direct subtypes को उसी source file में define होने तक सीमित कर देता है, जिससे compiler जांच सकता है कि कोई match expression हर संभव case को पूरी तरह से cover करता है या नहीं।

यह case classes के साथ मिलकर एक निश्चित, बंद set of variants (जैसे एक simple enum-style hierarchy) को model करने के लिए खासतौर पर शक्तिशाली है। अगर किसी sealed hierarchy पर match कोई case चूक जाए तो compiler warning देता है।

Note: case classes के साथ sealed आपको match expressions पर compiler-checked exhaustiveness warnings देता है -- एक बहुत आम, शक्तिशाली Scala pattern।

उदाहरण: Sealed Classes

markup
sealed trait Shape
case class Circle(radius: Double) extends Shape
case class Square(side: Double) extends Shape

object Main extends App {
  def area(shape: Shape): Double = shape match {
    case Circle(r) => Math.PI * r * r
    case Square(s) => s * s
  }

  println(area(Circle(2)))
  println(area(Square(3)))
}
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 trait की subclass को किसी दूसरे file में define करना, जो compile नहीं होता।
  2. किसी नए subclass को match में जोड़ना भूल जाना, जिससे compiler एक non-exhaustive match की चेतावनी देता है जिसे नज़रअंदाज़ कर दिया जाता है।
  3. match में एक case _ default जोड़ना, जो गायब subtype दिखाने वाली चेतावनी को छुपा देता है।
चैप्टर सारांश
  • Inheritance किसी class को दूसरी को extend करने और methods override करने देता है।
  • Abstract classes और traits shared behavior define करते हैं, और traits mix in किए जा सकते हैं।
  • Sealed classes subclasses के set को सीमित करती हैं।
🔒

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.