Home > Software engineering >  Why is this Kotlin-class an abstract class?
Why is this Kotlin-class an abstract class?

Time:01-28

I got this code somebody wrote:

abstract class ListItem {
    companion object {
        private var id = 0
        fun getUUID() = id  
    }
}

fun getItem(uuid: Int): ListItem? {
    for (dessert in Dessert.getAllDesserts())
        if (dessert.id == uuid)
            return dessert
    for (fruit in Fruit.getAllFruits())
        if (fruit.id == uuid)
            return fruit
    return null
}

Example of a sub-class:

data class Fruit(
    val id: Int,
    val resId: Int,
    val name: String,
    val origin: String,
    val desc: String
): ListItem() {
    companion object {
        private val fruits = listOf(
            Fruit(getUUID(), R.drawable.f1_durian, "Durian", "Indonesia", "Often dubbed the king of fruit, durian is an unusual tropical fruit that grows throughout Southeast Asia. A large spiky outer shell reveals a creamy, almost custard-like flesh, which, besides boasting a mildly sweet flavor, is notorious for being incredibly rank-smelling."), 

I don`t get why ListItem is an abstract class. There are no unimplemented methods.

What's the motivation making ListItem an abstract class?

Has someone an idea?

CodePudding user response:

Like the great example mr mcwolf gave, the 'problem' here is a conceptual one: although you could allow for the instantiation of a ListItem, what would its purpose be? It has no 'physical' meaning, if we're talking about food items.

However, it's important to note that an interface would be a better approach, as there are no actual benefits of using inheritance on the example you gave and it might even be misleading.

If, in this case, ListItem is turned into a 'marker' interface, it achieves the purpose of not being directly instantiable and helps with generic typing (if used later on, for example) while not breaking some other desired behavior (e.g. putting both Fruit and Dessert under a Food hierarchy).

  • Related