Is there a way to have a sealed class define an ab...
# announcements
m
Is there a way to have a sealed class define an abstract method and have the parameter smart casted to the subclass? Something like this:
Copy code
sealed class ItemType {
	data class Section(name: String) : ItemType() {
		override fun areContentsTheSame(other: ItemType.Section) = name == other.name
	}
	
	data class Item(value: Long): ItemType() {
		override fun areContentsTheSame(other: ItemType.Item) = value == other.value
	}
	
	abstract fun areContentsTheSame(other: ItemType): Boolean
}
m
Copy code
sealed class ItemType<T>(
    val item: T
){
    data class Section(val name: String) : ItemType<String>(name)
    data class Item(val value: Long) : ItemType<Long>(value)

    fun areContentsTheSame(other: ItemType<T>): Boolean = item == other.item
}
perhaps this is what you mean? Or at least in the right direction?
update:
Copy code
sealed class ItemType<T : ItemType<T>>{
    data class Section(val name: String) : ItemType<Section>(){
        public override fun areContentsTheSame(other: Section): Boolean = this.name == other.name
    }
    data class Item(val value: Long) : ItemType<Item>(){
        public override fun areContentsTheSame(other: Item): Boolean = this.value == other.value
    }

    protected abstract fun areContentsTheSame(other: T): Boolean
}
this is probably what you wanted
m
yes, that is exactly what i was looking for. thanks
m
the protected abstract can have a public visibility modifier depending on your need. however, I consider equality checks as a commutative operator.