Sealed classes or interface

5 0 0
                                        

sealed class or interface - this provides more restriction on who can use the code. It functions like a combination of a modifier and an enum. We know a modifier restricts while enum provides constants. So, if you combine, the sealed class or interface provides restriction on the object access.

1. sealed class constructor is protected by default. And it allows two modifiers which is protected and private.

2. sealed class is an abstract class. You can't create an object. You have to extend it before you can use it. It can contain abstract members too.

3. It requires a name for the class or interface.

4. Sealed classes cannot be part of the locals or become anonymous.

How useful?

The subclasses of a sealed class is known during compile time. So, when it is running and someone wants to access your class, they will not be allowed because they are not part of the sealed class known subclass. They are outside of your module. A module contains lots of files.

Two types:

1. direct subclass - it extended the sealed class or interface. This can be extended within the same package or  the same module depending on the modifier.

2. indirect subclass - it extended the class with a sealed class or interface extensions. It can be extended anywhere where it is visible to the user as long as the modifier allows it.

======================

// put this in one file

sealed class SealingThisData private constructor(){

    data class MyFavMusic(val song: String): SealingThisData()

}

data class MyFavDestination(val place: String): SealingThisData()

fun main(){

    val music = SealingThisData.MyFavMusic("2002")

    println(music.toString())

    val thePlace = MyFavDestination("My Place")

    println(thePlace.toString())

}

/* put this in another file.. the bold underline extension is an error

data class FavRockMusic(val song: String): SealingThisData()

*/

======================

Result:

MyFavMusic(song=2002)

MyFavDestination(place=My Place)


Note: 

1. Make sure to comment the data class with an error to run it.... 

2. Two data classes within the same file works but the other data class in a separate file didn't because the constructor was private. But if you use the default which is protected, all data classes will work.

3. Sealed class works well in a when expression.

4. There is a topic about sealed that relates to multiplatform. I did not try it because I am not there yet.

Kotlin ProgrammingWhere stories live. Discover now