mahdi sadeghi
mahdi sadeghi

Reputation: 68

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:

  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?

Upvotes: 1

Views: 183

Answers (1)

marstran
marstran

Reputation: 28056

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
    }
}

Upvotes: 2

Related Questions