Kotlin Sealed Class

Learn via video courses
Topics Covered

Overview

Sealed classes in Kotlin are exceptional classes that maintain a restricted hierarchy, that is, they can only be subclassed within the same file where they are initialized.Sealed class kotlin are used to represent restricted class hierarchies, often used in scenarios where a class can have a fixed set of subclasses, and no other classes can extend them from outside the file.

The main benefit of sealed classes kotlin is that they provide*enhanced control over inheritance, making it easier to manage a closed set of subclasses.

Transform Your Career

Choose from our industry-leading programs designed for career success

NSDC Certified

Modern Software and AI Engineering Program

Master full-stack development with AI integration

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Modern Data Science and ML with specialisation in AI

Advanced data science techniques with AI specialization

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Advanced AIML with Specialisation in Agentic AI

Deep dive into AIML with focus on Agentic systems

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

DevOps, Cloud & AI Platform Engineering

Build and manage AI-powered cloud infrastructure

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

AI Engineering Advanced Certification by IIT-Roorkee

Premier AI engineering certification from IIT-Roorkee

3 MonthsDuration
AI-LedCurriculum
Career SupportSupport
Program highlights
Go to Program

Sealed Classes and Interfaces

Sealed class kotlin manage hierarchy restrictions, interfaces facilitate code abstraction and modularity, allowing classes to adhere to various contracts, improving the overall design and maintainability of the codebase.

Sealed Classes Example:

Imagine you have a game that involves different types of balls, such as SoccerBall, Basketball, and TennisBall. You can create a sealed class called Ball and define these types as subclasses of the sealed class kotlin.

Whearas, an interface defines a contract with abstract methods that classes must implement, allowing multiple inheritance-like behaviours through implementing multiple interfaces.

When compared to sealed classes kotlin, interfaces serve as a blueprint for classes to fulfil specific contracts by implementing abstract methods.

They enable classes to achieve multiple inheritance-like behaviours through implementing multiple interfaces, promoting code flexibility and reusability.

Interface Example:

Consider a situation where you have different types of balloons, such as HeliumBalloon, WaterBalloon, and PartyBalloon. You can define an interface called Inflatable with an abstract method inflate(). Each balloon class can then implement the Inflatable interface, providing its implementation of the inflate() method.

Location of direct subclasses

Sealed class kotlin provide a convenient and structured way to define a restricted class hierarchy. By having all the subclasses declared directly within the sealed class's body, Kotlin ensures that developers can easily manage and understand the relationship between the sealed class kotlin and its subclasses.

Location of direct subclasses

Turn Learning into Career Growth

1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary
1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary

Inheritance in multiplatform projects

In Kotlin multiplatform projects (Kotlin MPP), inheritance works similarly to traditional Kotlin projects with some platform-specific considerations. Kotlin MPP allows you to share code between different platforms, such as JVM, Android, iOS, and JavaScript, while also providing the flexibility to write platform-specific code when needed.

Inheritance in Kotlin MPP allows you to define common classes and interfaces in the shared codebase and then provide platform-specific implementations in platform-specific modules. The shared codebase can include abstract classes, interfaces, and regular classes that can be extended or implemented by platform-specific code.

In Kotlin, you can create a shared abstract class "Shape" with properties like "name" and "colour". Platform-specific subclasses, such as "AndroidShape" or "iOSShape", can implement platform-specific features.

For example, "AndroidShape" may use Android graphics libraries for rendering, while "iOSShape" utilizes iOS-specific frameworks. This approach enables code sharing, ensuring a consistent shape-related experience across various platforms.

Scaler Placement Report and Statistics

₹23L
AVG CTC
SCALER PLACEMENT PROOF

Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L.

11,000+placements
650+companies
Verified data

Sealed classes and when expression

The when expression in Kotlin is similar to a switch or case statement in other programming languages. It allows you to check the value of an expression against multiple cases and execute the code block associated with the first matching case.

When you use the when expression with a kotlin sealed class, it becomes particularly powerful. Since a sealed class kotlin can only have a limited set of subclasses defined within the same file, the when expression can handle all possible cases exhaustively.

The exhaustive handling is possible because the compiler knows all the subclasses of the sealed class kotlin and can ensure that you cover all cases in the when expression. This is useful because it helps catch any missing cases during compile time, reducing the chances of runtime errors due to unhandled cases.

Code:

Output:

Explaination:

In this example, we have a sealed class kotlin called Status with three subclasses: Idle, Running, and Finished. The when expression inside the handleStatus function checks the value of the status parameter and prints a message based on the specific subclass. When you call handleStatus with different instances of Status, it will print the corresponding message associated with that status.

Conclusion

  • Sealed classes in Kotlin have a limited and fixed set of subclasses declared within the same file, providing a restricted class hierarchy.
  • They offer enhanced control over inheritance, as subclasses cannot be extended from outside the sealed class's file.
  • The when expression combined with sealed class kotlin enables exhaustive pattern matching, ensuring all possible cases are handled.
  • All subclasses of a sealed class are directly located within the sealed class, promoting code readability and maintainability.
  • In Kotlin multiplatform projects, inheritance allows sharing of common code while implementing platform-specific features.
Hiring Partners:
GoogleGoogleAmazonAmazonMicrosoftMicrosoftFlipkartFlipkartAdobeAdobe1200+ more