In the kind of application I’m doing, which involves trees and graphs, sealed class helps me a lot. I couldn’t give that up without my code getting messy. I use to make generic nodes that can assume many analogous but not equal types. It’s a kind of union type.
However, I have some small complaints.
a) I cannot (unless I use the clumsy relflection or make custom changes in any sealead class that I declare) scan all subclasses, for instance, when I use copy
function. The new sealedSubclasses
feature is not enough.
b) I cannot make a dummy initialization with some subclass, because I cannot reassign with other subclass. It’s not a big deal, and if one needs to initializate, one should declare sealed classes instances always using ?
, in order to be initialized with null
. It’s not cool, because it infringes the null safety feature in Kotlin. Normal usage of sealed classes instances is inside conditional blocks, so I need always make a generic initialization.
Normally Kotlin accepts assign common properties in a sealed class, however with nullable variables, it force to use “!!” operator in a normal assign. Null exception is possible here.
var mySealed:MySealed?=null
mySealed.commonProp = 25!!
A reasonable solution here is always to use lateinit i
n the variable declaration