Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the difference between open class and sealed class in Kotlin?

I think that whatever can be done with sealed class can be done with open class as well. So what is the advantage of using sealed class?
for example:

sealed class:

  sealed class Test {
        class StressTest(val message: String) : Test()
    }

open class:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  open class Test {
        class StressTest(val message: String) : Test()
    }

implementation:

when(test) {
                is Test.StressTest -> TODO()
            }

It doesn’t matter if our class is sealed or open, this implementation is correct for both.

So, what is the reason for using Sealed class? What is the difference between the two? Does anyone know the answer to this question?

>Solution :

The difference is that you get better exhaustiveness checks when using a sealed class. A sealed class guarantees that there are no other subclasses than the ones you have defined in your module.

You will see the difference if you capture the result of your when-expression in a variable:

sealed class Test {
    class StressTest(val message: String) : Test()
}

suspend fun main() {
    val test: Test = Test.StressTest("StressTest")
    
    // When is exhaustive -> it compiles.
    val res = when(test) {
        is Test.StressTest -> 5
    }
}

versus

open class Test {
    class StressTest(val message: String) : Test()
}

suspend fun main() {
    val test: Test = Test.StressTest("StressTest")
    
    // When is not exhaustive -> it does not compile.
    val res = when(test) {
        is Test.StressTest -> 5
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading