Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between sealed class vs sealed interface in kotlin

With Kotlin 1.5 was introduce the sealed interface. Even that I know the difference between classes and interfaces, I'm not clear what are the best practices and beneficies of using sealed interface over sealed class

Should I always use interface now even when is a simple case? Or will be a case by case?

Thanks

Obs: Didn't found similar questions, only about sealed classes

like image 403
Canato Avatar asked Sep 08 '21 09:09

Canato


1 Answers

A major reason to choose to use a sealed class instead of interface would be if there is common property/function that you don't want to be public. All members of an interface are always public.

The restriction that members must be public can be worked around on an interface using extension functions/properties, but only if it doesn't involve storing state non-publicly.

Otherwise, sealed interfaces are more flexible because they allow a subtype to be a subclass of something else, an enum class, or a subtype of multiple sealed interface/class hierarchies.

like image 152
Tenfour04 Avatar answered Sep 27 '22 18:09

Tenfour04