Extending data class from a sealed class in Kotlin

后端 未结 1 1960
渐次进展
渐次进展 2020-12-29 01:58

I have a set of data classes that share some common fields, So ideally I\'d like to declare those in a supertype (Message in this example), and be able to write functions th

相关标签:
1条回答
  • 2020-12-29 02:07

    Options 3 and 4 would result in the class holding messageId twice. Once in the new class and once in its superclass.

    The solution is to declare but not define the variable in the superclass:

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

    This will make the messageId available on Message, but delegates the storage to whatever implements it.

    0 讨论(0)
提交回复
热议问题