Data class doesn't use overridden method from sealed class

Hello!

I have a sealed class, DeliveryOption, where I override the toString method, but when I call it from Guy or Dispatcher it looks like it’s not overridden and returns the base implementation of toString.

Why is it not calling the override one?

sealed class DeliveryOption {
    abstract val id: Int
    abstract val name: String

    override fun toString(): String = name
    
   data class Guy(
        override val id: Int,
        override val name: String
    ) : DeliveryOption()

    data class Dispatcher(
        override val id: Int,
        override val name: String
    ) : DeliveryOption() 
}

data classes define their own toString which does override whatever toString there might be in a superclass.
Your options are:

  1. override toString individually for Guy and Dispatecher and remove the override in DeliveryOption since it’s unreachable
  2. Use another method which returns a String that you define once and for all in DeliveryOption
  3. Drop the data modifier from Guy and Dispatecher
2 Likes

To retain a toString() implementation from the base you can declare the method as final:

sealed class DeliveryOption {
	abstract val id: Int
	abstract val name: String
	
	final override fun toString(): String = name
	
	data class Guy(
		override val id: Int,
		override val name: String
	) : DeliveryOption()
	
	data class Dispatcher(
		override val id: Int,
		override val name: String
	) : DeliveryOption()
}
7 Likes

That’s clever, I never thought of that!