Data class extend sealed class

I recently face problems of extending sealed class in data class . The same with this SO link

The solution is OK :

sealed class Message {
    abstract val messageId: String
}
data class Track(val event: String, override val messageId: String): Message()

But I wonder why Option2 is not supported ?

sealed class Message(val messageId: String)
data class Track(val event: String, messageId: String): Message(messageId)

It seems intuitional (and maybe more ideal) , but pity it’s not supported.

Yes , I know the reason :

(“Data class primary constructor must have only property (val/var) parameters.”)

But I think it should be able to infer it as a superclass’s val parameter and passes.

Just my 2 cents.

1 Like

It’s compatible.
According to the references:

To declare an explicit supertype, we place the type after a colon in the class header:
If the derived class has a primary constructor, the base class can (and must) be initialized right there, using the parameters of the primary constructor.

https://kotlinlang.org/docs/reference/classes.html

In the code, the class was declared as open and the value of the subclass with override.

open:

The open annotation on a class is the opposite of Java’s final: it allows others to inherit from this class. By default, all classes in Kotlin are final, which corresponds to Effective Java, Item 17: Design and document for inheritance or else prohibit it.

override:

Annotation override signals the overriding of base method by inheriting class.

The code would be like this:

sealed class Message(open val messageId: String)
data class Track(val event: String, override val messageId: String) : Message(messageId)
3 Likes

Wow , thanks for great help !